angular.module('starter.services', [])
  //顶上提示框
  .factory('$BPTopAlert', [
    '$rootScope',
    '$compile',
    '$animate',
    '$timeout',
    '$ionicBody',
  function ($rootScope, $compile, $animate, $timeout, $ionicBody) {
      return {
          show: topAlert
      };
      function topAlert(opts) {
          var scope = $rootScope.$new(true);
          ionic.extend(scope, {
              text: "提示消息",
              timeout: 1500
          }, opts || {});
          // Compile the template
          var element = scope.element = $compile('<div class="nav-title-slide-ios7 bar bar-header lr-topAlert"><div class="title title-center header-item" >{{text}}</div></div>')(scope);
          // removes the actionSheet from the screen
          scope.removeSheet = function () {
              if (scope.removed) return;
              scope.removed = true;
              $animate.removeClass(element, 'active').then(function () {
                  scope.$destroy();
                  element.remove();
              });
          };
          scope.showSheet = function () {
              if (scope.removed) return;
              $ionicBody.append(element);
              $animate.addClass(element, 'active');
          };
          scope.showSheet();
          $timeout(function () {
              scope.removeSheet();
          }, scope.timeout);

          return null;
      }
  }])
  
  //配置图片选择
  .factory('$SelectPicture',['$rootScope','$BPUploadFile','ApiUrl','$cordovaImagePicker','$BPTopAlert','$ionicLoading','$cordovaCamera',function($rootScope,$BPUploadFile,ApiUrl,$cordovaImagePicker,$BPTopAlert,$ionicLoading,$cordovaCamera) {
	  var scope = $rootScope.$new(true);
	  return {
		chooseSinglePicture:function(opts) {
			
			ionic.extend(scope, {
				  data: {},
				  error: function () { }
			}, opts || {});
			
			var width=opts.width;
			var height=opts.height;
			document.addEventListener("deviceready", onDeviceReady, false);
			function onDeviceReady() {
				var options = {//相机配置
				  quality: 50,
				  //targetWidth: 1024,
				  //targetHeight: 768,
				  
				  destinationType: Camera.DestinationType.FILE_URI,
				  sourceType: Camera.PictureSourceType.CAMERA,
				  allowEdit: true,
			      encodingType: Camera.EncodingType.JPEG,
				  popoverOptions: CameraPopoverOptions,
				  saveToPhotoAlbum: false
				  
				  /*
				  allowEdit: false,
				  correctOrientation: false,
				  saveToPhotoAlbum: false,
				  // iOS
				  popoverOptions: CameraPopoverOptions,
				  // Basic
				  encodingType: Camera.EncodingType.JPEG,
				  sourceType: Camera.PictureSourceType.CAMERA,
				  destinationType: Camera.DestinationType.NATIVE_URI*/
				}
				$cordovaCamera.getPicture(options).then(
				  function(res){
					$ionicLoading.show();
					$BPUploadFile.uploadFile(
					{
						  "fileUrl": res,
						  "server": ApiUrl.uploadFileApi,
						  "success": function (result_Data) {
							  var return_data=JSON.parse(result_Data.response);
							  var return_desc=return_data.status.desc;
							  return_data=JSON.parse(return_desc);
							  scope.success(return_data);
							  $ionicLoading.hide();
						  },
						  "err":function(erro){
							  $BPTopAlert.show({ text: "文件上传失败！" });
							  $ionicLoading.hide();
						  }
					});
				  }
				);
			}
		},
		choosePictures: function(opts) {
		    var scope = $rootScope.$new(true);
			ionic.extend(scope, {
				  data: {},
				  error: function () { }
			}, opts || {});
			var options = {
				maximumImagesCount: 10,
				quality: 80
			};
			$cordovaImagePicker.getPictures(options)
				.then(function(res) {
					if(res.length>0)
						$ionicLoading.show();
					var data=[];
					var re_count=0;
					for(var i = 0; i < res.length; i++){
					  $BPUploadFile.uploadFile(
					  {
						  "fileUrl": res[i],
						  "server": ApiUrl.uploadFileApi,
						  "success": function (result_Data) {
							  re_count++;
							  var return_data=JSON.parse(result_Data.response);
							  var return_desc=return_data.status.desc;
							  return_data=JSON.parse(return_desc);
							  //console.log(return_data);
							  //console.log(return_desc);
							  scope.success(return_data);
							  if(re_count==res.length)
							  {
								  $ionicLoading.hide();
							  }
						  },
						  "err":function(erro){
							  re_count++;
							  $BPTopAlert.show({ text: "文件上传失败！" });
							  if(re_count==res.length)
							  {
								  $ionicLoading.hide();
							  }
						  }
					  });//传递自己的服务器接口地址
					}
				   //console.log("返回");
				   					
				}, function(error) {
					//$BPTopAlert.show({ text: "文件选取未能完成！" });
			});
		}
	  }
  }])
  
  //文件上传
  .factory('$BPUploadFile',['$BPTopAlert','$rootScope','$base64','UserInfo',function($BPTopAlert,$rootScope, $base64,UserInfo) {
	  
	  return {
		/**
		 * 上传文件到服务器
		 *
		 * @param fileUrl 文件路径
		 * @param server 服务器接口
		 */
		uploadFile: function(opts) {
		  var scope = $rootScope.$new(true);
          ionic.extend(scope, {
				  data: {},
				  error: function () { }
			}, opts || {});
		  var fileUrl=opts.fileUrl;
		  var server=opts.server;
          var userInfo = UserInfo.get();
          var platform = ionic.Platform.platform();
		  document.addEventListener("deviceready", onDeviceReady, false);
		  function onDeviceReady() {
			var options = new FileUploadOptions();
			options.fileKey = "BPAppInfo";//后台获取文件的键值
			//console.log("文件名："+fileUrl.substr(fileUrl.lastIndexOf('/') + 1));
			options.fileName = fileUrl.substr(fileUrl.lastIndexOf('/') + 1);
			options.mimeType = "image/jpeg";
			options.chunkedMode = false;

			var params = {};//这里可添加自定义参数
			params.token = userInfo.token;
			params.userid = userInfo.userid;
			params.platform = platform;
            
			options.params = params;
			
			var headers={'Accept':'application/json, text/plain, */*'};
			options.headers = headers;
			
			var ft = new FileTransfer();
			ft.upload(fileUrl, 
					  encodeURI(server), 
					  success, 
					  err, 
					  options);
		  }
		  function success(r){
			  scope.success(r);
		  }

		  function err(error){
			  scope.err(error);
		  }
		}
	  }
	  
  }])
  .factory('$BPFlowSendData',['$BPHttp','$BPTopAlert','ApiUrl','$BPPopup','$ionicLoading','$BaseInfo','$BPUserSelectModal',
  function($BPHttp,$BPTopAlert,ApiUrl,$BPPopup,$ionicLoading,$BaseInfo,$BPUserSelectModal){
	  return {
			//发起流程 提交
			Start_Flow:function($scope,field_array){
				//判断流程名称和重要类型是否为空
				if($scope.editData.wflevel==undefined||$scope.editData.wflevel==null||$scope.editData.wflevel=="")
				{
					$BPTopAlert.show({ text: "请选择流程等级" });
				}
				else if($scope.editData.CustomName==undefined||$scope.editData.CustomName==null||$scope.editData.CustomName=="")
				{
					$BPTopAlert.show({ text: "请输入流程自定义标题" });
				}
				else{
					var type=0;//0直接发起 3为草稿模式
					
					type=$scope.editData.type;	
					var data=[];
					for(var i in field_array)
					{
						if(field_array[i].value==undefined) field_array[i].value="";
						if(field_array[i].realValue==undefined) field_array[i].realValue="";
						/*
						if(field_array[i].selfield)
							data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue});
						else
							data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue});
						*/
						if(field_array[i].isdel!=1){
							if(field_array[i].fieldType=="text")
							{
								if(field_array[i].selfield)
									data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue,control_rule:field_array[i].control_rule,control_uniq:field_array[i].control_uniq});
								else
									data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue,control_rule:field_array[i].control_rule,control_uniq:field_array[i].control_uniq});
							}
							else if(field_array[i].fieldType=="messageInfo"||field_array[i].fieldType=="currentInfo"||field_array[i].fieldType=="multiUserInfo")
							{
								if(field_array[i].selfield)
									data.push({infoType:field_array[i].infoType,type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue});
								else
									data.push({infoType:field_array[i].infoType,type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue});
							}
							else{
								if(field_array[i].selfield)
									data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue});
								else
									data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue});
							}
						}
						
					}
					var Description="";
					if($scope.editData.Description!=undefined&&$scope.editData.Description!=null&&$scope.editData.Description!="")
					{
						Description=$scope.editData.Description;
					}
					var _postData={"EnabledMark":1,"wfLevel":$scope.editData.wflevel,"Code":$scope.editData.flow.schemecode,"CustomName":$scope.editData.CustomName,"Description":Description};
					var data_send={ "wfSchemeInfoId": $scope.editData.flow.id, "frmData": JSON.stringify(data), "wfProcessInstanceJson": JSON.stringify(_postData), "type": type };
					$ionicLoading.show();
					$BPHttp.post({
						  "url": ApiUrl.createProcessApi,
						  "data": data_send,
						  "success": function (data) {
								$ionicLoading.hide();
								if(data.status.code=="0"){
									$BPTopAlert.show({ text: "数据提交成功！" });
									$scope.editModal.remove();
								}
								else{
									$BPTopAlert.show({ text: "数据提交错误！" });
								}
						  },
						  "error": function () {
							$BPTopAlert.show({ text: "数据提交错误" });
						  },
						  "finally": function () { 
								$ionicLoading.hide();
						  }
					});
				}
				//发送数据
			},
			//草稿发送
			Roughdraft_Process:function($scope,field_array,type){
				var data=[];
				for(var i in field_array)
				{
					if(field_array[i].value==undefined) field_array[i].value="";
					if(field_array[i].realValue==undefined) field_array[i].realValue="";
					if(field_array[i].isdel!=1){
						if(field_array[i].fieldType=="text")
						{
							if(field_array[i].selfield)
								data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue,control_rule:field_array[i].control_rule,control_uniq:field_array[i].control_uniq});
							else
								data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue,control_rule:field_array[i].control_rule,control_uniq:field_array[i].control_uniq});
						}
						else if(field_array[i].fieldType=="messageInfo"||field_array[i].fieldType=="currentInfo"||field_array[i].fieldType=="multiUserInfo")
						{
							if(field_array[i].selfield)
								data.push({infoType:field_array[i].infoType,type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue});
							else
								data.push({infoType:field_array[i].infoType,type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue});
						}
						else{
							if(field_array[i].selfield)
								data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue});
							else
								data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue});
						}
					}
				}
				var Description="";
				if($scope.editData.Description!=undefined&&$scope.editData.Description!=null&&$scope.editData.Description!="")
				{
					Description=$scope.editData.Description;
				}
				var _postData={"EnabledMark":3,"wfLevel":$scope.editData.wflevel,"Code":$scope.editData.flow.schemecode,"CustomName":$scope.editData.CustomName,"Description":Description};
				if(type!=0)
				{
					_postData.EnabledMark=1;
				}
				_postData.ProcessSchemeId=$scope.ProcessSchemeId;
				var data_send={ "wfSchemeInfoId": $scope.editData.flow.id, "frmData": JSON.stringify(data), "wfProcessInstanceJson": JSON.stringify(_postData)};
				//console.log(data_send);
				$ionicLoading.show();
				$BPHttp.post({
						  "url": ApiUrl.editionRoughdraftProcessApi,
						  "data": data_send,
						  "success": function (data) {
								$ionicLoading.hide();
								if(data.status.code=="0"){
									$BPTopAlert.show({ text: data.status.desc });
									$scope.editModal.remove();
									$scope.doRefresh();
								}
								else{
									$BPTopAlert.show({ text: data.status.desc  });
								}
						  },
						  "error": function () {
							$BPTopAlert.show({ text: "数据提交错误" });
						  },
						  "finally": function () { 
								$ionicLoading.hide();
						  }
				});
			},
			//流程审批数据提交
			Verification_Process:function($scope,field_array,type){
				var _postdata ={Createusername:$scope.editData.flow.createUserName,Description:$scope.editData.flow.description,VerificationUser:$scope.userinfo.realname,VerificationFinally:"",NodeRejectStep:$scope.editData.NodeRejectStep,VerificationOpinion:""};
				if($scope.editData.VerificationOpinion!=undefined&&$scope.editData.VerificationOpinion!=null&&$scope.editData.VerificationOpinion!=""){
					//console.log($scope.editData.VerificationOpinion);
					_postdata.VerificationOpinion=$scope.editData.VerificationOpinion;
				}
				if($scope.editData.VerificationFinally!=undefined||$scope.editData.VerificationFinally!=null||$scope.editData.VerificationFinally!=""){
					if($scope.editData.VerificationFinally=="发送")
						_postdata.VerificationFinally="1";
					if($scope.editData.VerificationFinally=="终止")
						_postdata.VerificationFinally="2";
					if($scope.editData.VerificationFinally=="驳回")
						_postdata.VerificationFinally="3";
					if($scope.editData.VerificationFinally=="移交")
						_postdata.VerificationFinally="4";
				}
				var data=[];
				for(var i in field_array)
				{
					if(field_array[i].value==undefined) field_array[i].value="";
					if(field_array[i].realValue==undefined) field_array[i].realValue="";
					if(field_array[i].isdel!=1){
						if(field_array[i].fieldType=="text")
						{
							if(field_array[i].selfield)
								data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue,control_rule:field_array[i].control_rule,control_uniq:field_array[i].control_uniq});
							else
								data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue,control_rule:field_array[i].control_rule,control_uniq:field_array[i].control_uniq});
						}
						else if(field_array[i].fieldType=="messageInfo"||field_array[i].fieldType=="currentInfo"||field_array[i].fieldType=="multiUserInfo"){
							if(field_array[i].selfield)
								data.push({infoType:field_array[i].infoType,type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue});
							else
								data.push({infoType:field_array[i].infoType,type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue});
						}
						else{
							if(field_array[i].selfield)
								data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue});
							else
								data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue});
						}
					}
				}
				var data_send={ "processId": $scope.editData.flow.id, "verificationData": JSON.stringify(_postdata), "frmData":  JSON.stringify(data), "EnabledSave": 0, "activityId": $scope.editData.flow.activityId,"makeLists":"" };
					
				if(type==0)
				{
					$ionicLoading.show();
					//保存数据
					data_send.EnabledSave=1;
					$BPHttp.post({
						  "url": ApiUrl.verificationProcessApi,
						  "data": data_send,
						  "success": function (data) {
								$ionicLoading.hide();
								if(data.status.code=="0"){
									$BPTopAlert.show({ text: "数据保存成功！" });
									$scope.editModal.remove();
									$scope.doRefresh();
								}
								else{
									$BPTopAlert.show({ text: "数据保存错误！" });
								}
						  },
						  "error": function () {
							$BPTopAlert.show({ text: "数据保存错误" });
						  },
						  "finally": function () { 
								$ionicLoading.hide();
						  }
					});
				}
				else{
					if($scope.editData.VerificationFinally==undefined||$scope.editData.VerificationFinally==null||$scope.editData.VerificationFinally=="")
					{
						$BPTopAlert.show({ text: "请选择处理结果" });
					}
					else if($scope.editData.VerificationFinally=="移交"){
						//打开移交数据
						$scope.RadioSideList=$BaseInfo.getDepartmentUserInfo();
						$BPUserSelectModal({title:"选择用户",bgAllColor:"positive-bg",selectValue:"",data:$scope.RadioSideList,
							onChange: function (item) {
								data_send.makeLists=item.userId;
								$ionicLoading.show();
								$BPHttp.post({
								  "url": ApiUrl.verificationProcessApi,
								  "data": data_send,
								  "success": function (data) {
										$ionicLoading.hide();
										if(data.status.code=="0"){
											$BPTopAlert.show({ text: "数据提交成功！" });
											$scope.editModal.remove();
											$scope.doRefresh();
										}
										else{
											$BPTopAlert.show({ text: "数据提交错误！" });
										}
								  },
								  "error": function () {
										$BPTopAlert.show({ text: "数据提交错误" });
								  },
								  "finally": function () { 
										$ionicLoading.hide();
								  }
								});
							}
						 });
					}
					else{
						var NodeRejectCheck=true;
						if($scope.editData.VerificationFinally=="驳回"&&$scope.ShowNodeRejectStep==1)
						{
							if($scope.editData.NodeRejectStep==undefined||$scope.editData.NodeRejectStep==null||$scope.editData.NodeRejectStep=="")
							{
								$BPTopAlert.show({ text: "请选择驳回步骤" });
								NodeRejectCheck=false;
							}
						}
						//console.log(data_send);
						if(NodeRejectCheck){
							$ionicLoading.show();
							$BPHttp.post({
							  "url": ApiUrl.verificationProcessApi,
							  "data": data_send,
							  "success": function (data) {
									$ionicLoading.hide();
									if(data.status.code=="0"){
										$BPTopAlert.show({ text: "流程处理成功！" });
										$scope.editModal.remove();
										$scope.doRefresh();
									}
									else{
										$BPTopAlert.show({ text: "流程处理错误！" });
									}
							  },
							  "error": function () {
								$BPTopAlert.show({ text: "流程处理错误" });
							  },
							  "finally": function () { 
									$ionicLoading.hide();
							  }
							});
						}
					}
				}
			}
	  };
  }])
  //流程表单解析
  .factory('$BPFlowStartMethod',['$BPHttp','$BPTopAlert','$BaseInfo','$BPFormDesign','$ionicModal','$ionicLoading','ApiUrl','UserInfo','$BPValidform','$BPFormatDate','$BPFlowSendData',
   function($BPHttp,$BPTopAlert,$BaseInfo,$BPFormDesign,$ionicModal,$ionicLoading,ApiUrl,UserInfo,$BPValidform,$BPFormatDate,$BPFlowSendData){
	    $BaseInfo.init();//初始化基础信息
		
		function sendDataInit($scope,item,field_list,self_field_list,field_array,Validateflag)
		{
			  var formData = "";
			  var isneedCheck = 0;

			  for(var j=0;j<field_array.length; j++)
			  {
				  if(field_array[j].control_uniq==1)
				  {
					 //console.log(field_array[j]);
					  if(formData!="")formData+=",";
					  isneedCheck=1;
					  if(field_array[j].selfield)
						formData += '{"FrmID":"' + $scope.frmEntity.FrmId + '","FieldID":"' + field_array[j].selfield + '","ID":"' + field_array[j].id + '","Data":"' + field_array[j].realValue + '","control_uniq_msg":"'+field_array[j].control_uniqmsg+'"}';
					  else
						formData += '{"FrmID":"' + $scope.frmEntity.FrmId + '","FieldID":"' + field_array[j].field + '","ID":"' + field_array[j].id + '","Data":"' + field_array[j].realValue + '","control_uniq_msg":"'+field_array[j].control_uniqmsg+'"}';  

				  }
			  }
			  
			  if (isneedCheck == 0)
			  {
				$BPFlowSendData.Start_Flow($scope,field_array);
			  }
			  else if (isneedCheck == 1) {
				formData = "[" + formData + "]";
				//console.log(formData);
				$ionicLoading.show();

				$BPHttp.post({
					  "url": ApiUrl.getUniqueCode,
					  "data": { "formData": formData},
					  "success": function (data) {
							$ionicLoading.hide();
							var formDataList=[];
							formDataList=JSON.parse(formData);
							if(data.status.desc!= ""){
								var fields = data.status.desc.split(',');
								for (var i = 0; i < fields.length; i++) {
									var msg="";
									for(var j in formDataList)
									{
										if(formDataList[j].ID==fields[i])
										{
											msg=formDataList[j].control_uniq_msg;
											break;
										}
									}
									$BPTopAlert.show({ text: msg });
									break;
								}

							}
							else{
								$BPFlowSendData.Start_Flow($scope,field_array);
							}
					  },
					  "error": function () {
						$BPTopAlert.show({ text: "数据获取错误" });
					  },
					  "finally": function () { 
							$ionicLoading.hide();
					  }
				 });
			  }
		}
		
		
		
		return {
			//草稿提交
			RoughdraftForm:function($scope,type)
			{
				var item=$scope.FrmContent;
				var field_list= $scope.form_field;
				var self_field_list= $scope.self_form_field;
				var field_array=[];
				for (var j = 0; j < item.length; j++) {
					for(var count=0;count<item[j].fields.length;count++)
					{
						if(item[j].fields[count].isdel==0)
						field_array.push(item[j].fields[count]);
					}
				}
				var Validateflag=true;
				  for(var j=0;j<field_array.length; j++)
				  {
					  var field_id=field_array[j].field;
					  
					  
					  if(field_array[j].fieldType=="datetime")
					  {
						  if(field_array[j].dateformat == "date")
						  {
							$scope.editData[field_id]=$BPFormatDate($scope.editData[field_id], "yyyy-MM-dd");
						  }
						  else
						  {
							$scope.editData[field_id]=$BPFormatDate($scope.editData[field_id], "yyyy-MM-dd hh:mm");
						  }
					  }
					  if(field_array[j].fieldType=='multiupload'||field_array[j].fieldType=='image'||field_array[j].fieldType=='upload')
					  {
						  var file_list="";
						  for(var i in $scope.editData[field_id])
						  {
							  if(file_list!="")file_list+=",";
							  file_list+=$scope.editData[field_id][i].fileId;
						  }
						  $scope.editData[field_id+"_listxx_Content"]=file_list;
					  }
					  field_array[j].value=$scope.editData[field_id];
					  if($scope.editData[field_id+"_listxx_Content"]!=""&&$scope.editData[field_id+"_listxx_Content"]!=undefined){
						  field_array[j].realValue=$scope.editData[field_id+"_listxx_Content"];
						  field_array[j].value=$scope.editData[field_id+"_listxx_Content"]; 
					  }
					  else if($scope.editData[field_id+"_txt"]!=""&&$scope.editData[field_id+"_txt"]!=undefined){
						field_array[j].realValue=$scope.editData[field_id+"_txt"];
					  }
					  else
						field_array[j].realValue=$scope.editData[field_id];  
					  if(field_array[j].verify!="")
					  {
						  var ops={};
						  
						  ops.value=field_array[j].value;
						  ops.checkexpession=field_array[j].verify;
						  ops.errormsg=field_array[j].label;
						  
						  Validateflag=$BPValidform(ops);
						  if(Validateflag==false)
							  break;
					  }
				  }
				  if(Validateflag!=false)
				  {
					 $BPFlowSendData.Roughdraft_Process($scope,field_array,type);
				  }
			},
			//审核表单数据处理
			VerificationForm:function($scope,type)
			{
				  var item=$scope.FrmContent;
				  
				  var field_list= $scope.form_field;
				  var self_field_list= $scope.self_form_field;
				  var field_array=[];
				  
				  for (var j = 0; j < item.length; j++) {
					for(var count=0;count<item[j].fields.length;count++)
					{
						if(item[j].fields[count].isdel==0)
						field_array.push(item[j].fields[count]);
					}
				  }
				  //console.log(field_array);
				  var Validateflag=true;
				  for(var j=0;j<field_array.length; j++)
				  {
					  var field_id=field_array[j].field;
					  
					  
					  if(field_array[j].fieldType=="datetime")
					  {
						  if(field_array[j].dateformat == "date")
						  {
							$scope.editData[field_id]=$BPFormatDate($scope.editData[field_id], "yyyy-MM-dd");
						  }
						  else
						  {
							$scope.editData[field_id]=$BPFormatDate($scope.editData[field_id], "yyyy-MM-dd hh:mm");
						  }
					  }
					  if(field_array[j].fieldType=='multiupload'||field_array[j].fieldType=='image'||field_array[j].fieldType=='upload')
					  {
						  var file_list="";
						  for(var i in $scope.editData[field_id])
						  {
							  if(file_list!="")file_list+=",";
							  file_list+=$scope.editData[field_id][i].fileId;
						  }
						  $scope.editData[field_id+"_listxx_Content"]=file_list;
					  }
					  field_array[j].value=$scope.editData[field_id];
					  if($scope.editData[field_id+"_listxx_Content"]!=""&&$scope.editData[field_id+"_listxx_Content"]!=undefined){
						  field_array[j].realValue=$scope.editData[field_id+"_listxx_Content"];
						  field_array[j].value=$scope.editData[field_id+"_listxx_Content"]; 
					  }
					  else if($scope.editData[field_id+"_txt"]!=""&&$scope.editData[field_id+"_txt"]!=undefined){
						field_array[j].realValue=$scope.editData[field_id+"_txt"];
					  }
					  else
						field_array[j].realValue=$scope.editData[field_id];  
					  if(field_array[j].verify!="")
					  {
						  var ops={};
						  
						  ops.value=field_array[j].value;
						  ops.checkexpession=field_array[j].verify;
						  ops.errormsg=field_array[j].label;
						  
						  Validateflag=$BPValidform(ops);
						  if(Validateflag==false)
							  break;
					  }
				  }
				  if(Validateflag!=false)
				  {
					 $BPFlowSendData.Verification_Process($scope,field_array,type);
				  }
			},
			//草稿编辑
			openFlowRoughdraftModal:function($scope,flow){
				$ionicLoading.show();
				$scope.BillCode=[];
				$scope.editData.flow=flow;
				//console.log(flow);
				$BPHttp.post({
						  "url": ApiUrl.getRoughdraftInfoJsonApi,
						  "data": {
							  keyValue: flow.id
						  },
						  "isverify": true,
						  "success": function (redata) {
								var data=redata.result;
								var items="";
								var schemeContent = JSON.parse(JSON.parse(data.processScheme.schemeContent).SchemeContent);
							  
								var selftdata = JSON.parse(JSON.parse(data.processScheme.schemeContent).frmData);
								var dataJson = JSON.parse(data.formEntity.frmContent);
							  
								$scope.form_field=[];
								$scope.self_form_field=[];
								if (data.formEntity.frmType != 2) {
									var filterJson = JSON.parse(data.formFilter);
									var filter_id = filterJson.map(function (item) { return item.id; });
									var filter_edit = filterJson.map(function (item) { return item.edit; });
									var tj=0;
									for (var j = 0; j < dataJson.data.length; j++) {
										for ( i = 0; i <dataJson.data[j].fields.length; i++) {
											var keyTemp = dataJson.data[j].fields[i].id;
											var index_1 = filter_id.indexOf(keyTemp);
											
											if(data.formEntity.type == 0)
											{	
												$scope.form_field.push(dataJson.data[j].fields[i].field);
												dataJson.data[j].fields[i].selfield=dataJson.data[j].fields[i].field;
												dataJson.data[j].fields[i].field="f"+tj;
												$scope.self_form_field.push(dataJson.data[j].fields[i].field);
											}
											else{
												$scope.form_field.push(dataJson.data[j].fields[i].field);
												$scope.self_form_field.push(dataJson.data[j].fields[i].field);
											}
											
											
											if (index_1 < 0) {
												dataJson.data[j].fields[i].isdel=1;
											}
											else {
												dataJson.data[j].fields[i].isdel=0;
												dataJson.data[j].fields[i].edit = filter_edit[index_1];
											}
											dataJson.data[j].fields[i].fieldType=dataJson.data[j].fields[i].type;
											tj++;
										}
									};
									 $scope.ProcessSchemeId=data.processInstance.processSchemeId;

									 $scope.FrmContent=dataJson.data;
									 //console.log(dataJson.data);
									 items=$BPFormDesign.Preview(dataJson.data);
								}
								$scope.editData.CustomName=flow.customName;
								$scope.editData.Description=flow.description;
								if(flow.wfLevel==3)
								{
									$scope.editData.wfleveltext="一般";
									$scope.editData.wflevel="3";
								}
								if(flow.wfLevel==2)
								{
									$scope.editData.wfleveltext="普通";
									$scope.editData.wflevel="2";
								}
								if(flow.wfLevel==1)
								{
									$scope.editData.wfleveltext="重要";
									$scope.editData.wflevel="1";
								}
							    var html='<ion-modal-view>';
								html+='<ion-header-bar class="bar-stable nav-bar-block nav-title-slide-ios7">';
								html+='<button class="button button-clear" ng-click="closeEditModal()"><i class="icon ion-ios-close-empty"></i></button>';
								html+='<h1 class="title">{{editData.flow.code}}</h1>';
								html+='<div class="buttons">';
								html+='	<button class="button button-clear" ng-click="doSubmit(0)"><i class="icon ion-ios-compose-outline"></i></button>';
								html+='	<button class="button button-clear" style="margin-left:5px;" ng-click="doSubmit(1)"><i class="icon ion-android-checkmark-circle"></i></button>';
								html+='</div>';
								html+='</ion-header-bar>';
								html+='<ion-content>';
								html+='<ion-list class="lr-list-form">';
								html+='<div class="item item-divider">';
								html+='自定义标题 <span>*</span>';
								html+='</div>';
								html+='<ion-item class="item-input">';
								html+='<div class="lr-form-input"><i class="icon ion-ios-drag"></i>添加自定义标题</div>';
								html+='<input type = "text" ng-model="editData.CustomName" ng-class="{\'active\' : isInputActive(\'CustomName\')}" />';
								html+='</ion-item>';
								html+='<div class="item item-divider">';
								html+='重要等级 <span>*</span>';
								html+='</div>';
								html+='<ion-item ng-click="openFlowLevelModal()">';
								html+='<div class="lr-form-select" ng-hide="editData.wfleveltext != null"><i class="icon ion-ios-drag"></i>添加重要等级</div>';
								html+='<div class="item-icon-right" ng-hide="editData.wfleveltext == null">';
								html+='<div class="lr-form-label positive-bg">{{editData.wfleveltext}}</div>';
								html+='<i class="icon ion-chevron-right icon-accessory"></i>';
								html+='</div>';
								html+='</ion-item>';
								
								html+='<div class="item item-divider">';
								html+='流程备注 <span>*</span>';
								html+='</div>';
								html+='<ion-item class="item-input">';
								html+='<div class="lr-form-input"><i class="icon ion-ios-drag"></i>添加流程备注</div>';
								html+='<input type = "text" ng-model="editData.Description" ng-class="{\'active\' : isInputActive(\'Description\')}" />';
								html+='</ion-item>';
								
								
								html+=items;
								
								html+='</ion-list>';
								html+='</ion-content>';
								html+='</ion-modal-view>';
								$ionicLoading.hide();
								var modal=$ionicModal.fromTemplate(html, {scope: $scope,animation: 'slide-left-right',});
								$scope.editModal = modal;
								
								$scope.editModal.show();
								//数据初始化
							    for(var i in selftdata)
								 {
									var obj=selftdata[i];
									
									if(data.formEntity.frmType == 0)
									{
										var i=$scope.form_field.indexOf(obj.field);
										
										if(obj.value!=""&&obj.value!=undefined){
											if(obj.type=='messageInfo'){
												$scope.editData[$scope.self_form_field[i]]=obj.value;
												$scope.editData[$scope.self_form_field[i]+"_txt"]=obj.realValue;
												var messageList=[];
												if(obj.value!=undefined)
												{
													if(obj.value!="")
													{
														var records=JSON.parse(obj.value);
														if(records)
														{
															for(var i in records){
																records[i].files=[];
																if(records[i].file_list!="")
																{
																	//console.log(records[i].file_list);
																	var list=records[i].file_list.split(',');
																	for(var f in list)
																	{
																		for(var fileItem in fileList)
																		{
																			if(fileList[fileItem].fileId==list[f])
																			{
																				records[i].files.push(fileList[fileItem]);
																			}
																		}
																	}
																}
																messageList.push(records[i]);
															}
														}
													}
												}
												$scope.editData[$scope.self_form_field[i]+"_list"]=messageList;
												
											}
											else if(obj.type=='multiupload'||obj.type=='image'||obj.type=='upload'){
												var list=obj.value.split(',');
												$scope.editData[$scope.self_form_field[i]]=[];
												$scope.editData[$scope.self_form_field[i]+"_txt"]=[];
												for(var f in list)
												{
													for(var fileItem in fileList)
													{
														if(fileList[fileItem].fileId==list[f])
														{
															if($scope.editData[$scope.self_form_field[i]]==null)
															{
																  $scope.editData[$scope.self_form_field[i]]=[];
															}
															if($scope.editData[$scope.self_form_field[i]+"_txt"]==null)
															{
																  $scope.editData[$scope.self_form_field[i]+"_txt"]=[];
															}
															$scope.editData[$scope.self_form_field[i]].push(fileList[fileItem]);
															$scope.editData[$scope.self_form_field[i]+"_txt"].push(fileList[fileItem]);
														}
													}
												}
											}
											else{
												$scope.editData[$scope.self_form_field[i]]=obj.value;
												$scope.editData[$scope.self_form_field[i]+"_txt"]=obj.realValue;
											}
											
										}
									}
									else{
										if(obj.value!=""&&obj.value!=undefined){
											if(obj.type=='messageInfo'){
												$scope.editData[obj.field]=obj.value;
												$scope.editData[obj.field+"_txt"]=obj.realValue;
												var messageList=[];
												if(obj.value!=undefined)
												{
													if(obj.value!="")
													{
														var records=JSON.parse(obj.value);
														if(records)
														{
															for(var i in records){
																records[i].files=[];
																if(records[i].file_list!="")
																{
																	//console.log(records[i].file_list);
																	var list=records[i].file_list.split(',');
																	for(var f in list)
																	{
																		for(var fileItem in fileList)
																		{
																			if(fileList[fileItem].fileId==list[f])
																			{
																				records[i].files.push(fileList[fileItem]);
																			}
																		}
																	}
																}
																messageList.push(records[i]);
															}
														}
													}
												}
												$scope.editData[obj.field+"_list"]=messageList;
											}
											else if(obj.type=='multiupload'||obj.type=='image'||obj.type=='upload'){
												var list=obj.value.split(',');
												$scope.editData[obj.field]=[];
												$scope.editData[obj.field+"_txt"]=[];
												for(var f in list)
												{
													for(var fileItem in fileList)
													{
														if(fileList[fileItem].fileId==list[f])
														{
															if($scope.editData[obj.field]==null)
															{
																  $scope.editData[obj.field]=[];
															}
															if($scope.editData[obj.field+"_txt"]==null)
															{
																  $scope.editData[obj.field+"_txt"]=[];
															}
															$scope.editData[obj.field].push(fileList[fileItem]);
															$scope.editData[obj.field+"_txt"].push(fileList[fileItem]);
														}
													}
												}
											}
											else{
												$scope.editData[obj.field]=obj.value;
												$scope.editData[obj.field+"_txt"]=obj.realValue;
											}
											
										}
									}
								 }
							  
							  
						  },
						  "finally": function () { 
							$ionicLoading.hide();
						  }
				});
			},
			//流程审批
			openFlowEditModal:function($scope,flow)
			{
				$ionicLoading.show();
				$scope.editData.flow=flow;
				$scope.BillCode=[];
				$BPHttp.post({
						  "url": ApiUrl.getProcessSchemeEntityByNodeIdApi,
						  "data": {
							  keyValue: flow.processSchemeId,nodeId:flow.activityId
						  },
						  "isverify": true,
						  "success": function (redata) {
							    var data=redata.result;
								var items="";
								//console.log(flow);
								var schemeContent = JSON.parse(JSON.parse(data.processScheme.schemeContent).SchemeContent);
								$scope.NodeRejectStep=schemeContent.Flow.nodes;
								
								var _node = "";
								for (var i in schemeContent.Flow.nodes)
								{
									if (schemeContent.Flow.nodes[i].id == flow.activityId)
									{
										_node = schemeContent.Flow.nodes[i];
										break;
									}
								}

								if (_node.setInfo != undefined && _node.setInfo.NodeRejectType == "3")
								{
									$scope.ShowNodeRejectStep=1;
								}
								
								
								var dataJson = JSON.parse(data.formEntity.frmContent);
								$scope.frmEntity=data.formEntity;
								$scope.form_field=[];
								$scope.self_form_field=[];
								if (data.formEntity.frmType != 2) {
									var filterJson = JSON.parse(data.formModule.frmContent);
									var filter_id = filterJson.map(function (item) { return item.id; });
									var filter_edit = filterJson.map(function (item) { return item.edit; });
									var tj=0;
									for (var j = 0; j < dataJson.data.length; j++) {
										for ( i = 0; i <dataJson.data[j].fields.length; i++) {
											var keyTemp = dataJson.data[j].fields[i].id;
											var index_1 = filter_id.indexOf(keyTemp);
											
											if(data.formEntity.type == 0)
											{	
												$scope.form_field.push(dataJson.data[j].fields[i].field);
												dataJson.data[j].fields[i].selfield=dataJson.data[j].fields[i].field;
												dataJson.data[j].fields[i].field="f"+tj;
												$scope.self_form_field.push(dataJson.data[j].fields[i].field);
											}
											else{
												$scope.form_field.push(dataJson.data[j].fields[i].field);
												$scope.self_form_field.push(dataJson.data[j].fields[i].field);
											}
											
											
											if (index_1 < 0) {
												dataJson.data[j].fields[i].isdel=1;
											}
											else {
												dataJson.data[j].fields[i].isdel=0;
												dataJson.data[j].fields[i].edit = filter_edit[index_1];
											}
											

											dataJson.data[j].fields[i].fieldType=dataJson.data[j].fields[i].type;
											
											
											if(dataJson.data[j].fields[i].type=="text"||dataJson.data[j].fields[i].type=="textarea"||dataJson.data[j].fields[i].type=="texteditor")
											{
												if(dataJson.data[j].fields[i].type=="text")
												{
													if(dataJson.data[j].fields[i].control_rule=="1")
													{
														
														dataJson.data[j].fields[i].edit=false;
													}
												}
												$scope.editData[dataJson.data[j].fields[i].field]=dataJson.data[j].fields[i].defaultValue;
												$scope.editData[dataJson.data[j].fields[i].field+"_txt"]=dataJson.data[j].fields[i].defaultValue;
											}
											if(dataJson.data[j].fields[i].type=="datetime")
											{
												if(dataJson.data[j].fields[i].defaultValue="Today"){
													$scope.editData[dataJson.data[j].fields[i].field]=new Date();
												} else if(dataJson.data[j].fields[i].defaultValue="Yesterday")
												{
													var myDate=new Date();
													myDate.setDate(myDate.getDate()-1);
													$scope.editData[dataJson.data[j].fields[i].field]=myDate;
												} else if(dataJson.data[j].fields[i].defaultValue="Tomorrow")
												{
													var myDate=new Date();
													myDate.setDate(myDate.getDate()+1);
													$scope.editData[dataJson.data[j].fields[i].field]=myDate;
												}
											}
											if(dataJson.data[j].fields[i].type=="currentInfo")
											{
												$scope.userinfo = UserInfo.get();
												//console.log($scope.userinfo);
												if(dataJson.data[j].fields[i].infoType=="user")
												{
													$scope.editData[dataJson.data[j].fields[i].field]=$scope.userinfo.account;
													$scope.editData[dataJson.data[j].fields[i].field+"_txt"]=$scope.userinfo.realname;
												}
												if(dataJson.data[j].fields[i].infoType=="department")
												{
													$scope.editData[dataJson.data[j].fields[i].field]=$scope.userinfo.departmentid;
													$scope.editData[dataJson.data[j].fields[i].field+"_txt"]=$scope.userinfo.departmentname;
												}
												if(dataJson.data[j].fields[i].infoType=="organize")
												{
													$scope.editData[dataJson.data[j].fields[i].field]=$scope.userinfo.organizeid;
													$scope.editData[dataJson.data[j].fields[i].field+"_txt"]=$scope.userinfo.organizename;
												}
												if(dataJson.data[j].fields[i].infoType=="date")
												{
													$scope.editData[dataJson.data[j].fields[i].field]=$filter('date')(new Date(),'yyyy-MM-dd HH:mm:ss');
													$scope.editData[dataJson.data[j].fields[i].field+"_txt"]=$filter('date')(new Date(),'yyyy-MM-dd HH:mm:ss');
												}
											}											
											tj++;
										}
									}
									
									
									
									 $scope.FrmContent=dataJson.data;
									 //console.log(dataJson.data);
									 items=$BPFormDesign.Preview(dataJson.data);
									 //console.log($scope.editData.flow);
									 var html='<ion-modal-view>';
									 html+='<ion-header-bar class="bar-stable nav-bar-block nav-title-slide-ios7">';
									 html+='<button class="button button-clear" ng-click="closeEditModal()"><i class="icon ion-ios-close-empty"></i></button>';
									 html+='<h1 class="title">{{editData.flow.code}}/{{editData.flow.customName}}</h1>';
									 //html+='<button class="button button-clear" ng-click="doSubmit()"><i class="icon ion-ios-trash-outline"></i></button>';
									 
									 html+='<div class="buttons">';
									 html+='	<button class="button button-clear" ng-click="doSubmit(0)"><i class="icon ion-ios-compose-outline"></i></button>';
									 html+='	<button class="button button-clear" style="margin-left:5px;" ng-click="doSubmit(1)"><i class="icon ion-android-checkmark-circle"></i></button>';
									 html+='</div>';
									 
									 html+='</ion-header-bar>';
									 html+='<ion-content>';
									 html+='<ion-list class="lr-list-form">';
									 html+='<div class="item item-divider">';
									 html+='流程发起人 <span>*</span>';
									 html+='</div>';
									 html+='<ion-item class="item-input">';
									 html+='<div class="lr-form-input"><i class="icon ion-ios-drag"></i>添加流程发起人</div>';
									 html+='<input type = "text" ng-model="editData.flow.createUserName" ng-class="{\'active\' : isInputActive(\'createUserName\')}"  ng-disabled="true" />';
									 html+='</ion-item>';
									 html+='<div class="item item-divider">';
									 html+='处理结果 <span>*</span>';
									 html+='</div>';
									 html+='<ion-item ng-click="openFlowVerificationModal()">';
									 html+='<div class="lr-form-select" ng-hide="editData.VerificationFinally != null"><i class="icon ion-ios-drag"></i>添加处理结果</div>';
									 html+='<div class="item-icon-right" ng-hide="editData.VerificationFinally == null">';
									 html+='<div class="lr-form-label positive-bg">{{editData.VerificationFinally}}</div>';
									 html+='<i class="icon ion-chevron-right icon-accessory"></i>';
									 html+='</div>';
									 html+='</ion-item>';
									 
									 html+='<div class="item item-divider" ng-if="checkNodeRejectStep()">';
									 html+='驳回步骤 <span>*</span>';
									 html+='</div>';
									 html+='<ion-item ng-click="openFlowNodeRejectStepModal()" ng-if="checkNodeRejectStep()">';
									 html+='<div class="lr-form-select" ng-hide="editData.NodeRejectSteptext != null"><i class="icon ion-ios-drag"></i>驳回步骤</div>';
									 html+='<div class="item-icon-right" ng-hide="editData.NodeRejectSteptext == null">';
									 html+='<div class="lr-form-label positive-bg">{{editData.NodeRejectSteptext}}</div>';
									 html+='<i class="icon ion-chevron-right icon-accessory"></i>';
									 html+='</div>';
									 html+='</ion-item>';
									 
									 html+='<div class="item item-divider">';
								     html+='处理意见';
									 html+='</div>';
									 html+='<ion-item class="item-input">';
									 html+='<div class="lr-form-input"><i class="icon ion-ios-drag"></i>添加处理意见</div>';
									 html+='<input type = "text" ng-model="editData.VerificationOpinion" ng-class="{\'active\' : isInputActive(\'VerificationOpinion\')}" />';
									 html+='</ion-item>';
									 
									 html+=items;
										
									 html+='</ion-list>';
									 html+='</ion-content>';
									 html+='</ion-modal-view>';
									 
									 $ionicLoading.hide();
									 var modal=$ionicModal.fromTemplate(html, {scope: $scope,animation: 'slide-left-right',});
									 $scope.editModal = modal;
									 $scope.editModal.show();
									 
									 var selftdata=JSON.parse(JSON.parse(data.processScheme.schemeContent).frmData);
									 var fileList=JSON.parse(data.fileList);
									 for(var i in selftdata)
									 {
										var obj=selftdata[i];
										
										if(data.formEntity.type == 0)
										{
											var i=$scope.form_field.indexOf(obj.field);
											
											if(obj.value!=""&&obj.value!=undefined){
												if(obj.type=='messageInfo'){
													$scope.editData[$scope.self_form_field[i]]=obj.value;
													$scope.editData[$scope.self_form_field[i]+"_txt"]=obj.realValue;
													var messageList=[];
													if(obj.value!=undefined)
													{
														if(obj.value!="")
														{
															var records=JSON.parse(obj.value);
															if(records)
															{
																for(var i in records){
																	records[i].files=[];
																	if(records[i].file_list!="")
																	{
																		//console.log(records[i].file_list);
																		var list=records[i].file_list.split(',');
																		for(var f in list)
																		{
																			for(var fileItem in fileList)
																			{
																				if(fileList[fileItem].fileId==list[f])
																				{
																					records[i].files.push(fileList[fileItem]);
																				}
																			}
																		}
																	}
																	messageList.push(records[i]);
																}
															}
														}
													}
													$scope.editData[$scope.self_form_field[i]+"_list"]=messageList;
												}
												else if(obj.type=='multiupload'||obj.type=='image'||obj.type=='upload'){
													var list=obj.value.split(',');
													$scope.editData[$scope.self_form_field[i]]=[];
													$scope.editData[$scope.self_form_field[i]+"_txt"]=[];
													for(var f in list)
													{
														for(var fileItem in fileList)
														{
															if(fileList[fileItem].fileId==list[f])
															{
																if($scope.editData[$scope.self_form_field[i]]==null)
																{
																	  $scope.editData[$scope.self_form_field[i]]=[];
																}
																if($scope.editData[$scope.self_form_field[i]+"_txt"]==null)
																{
																	  $scope.editData[$scope.self_form_field[i]+"_txt"]=[];
																}
																$scope.editData[$scope.self_form_field[i]].push(fileList[fileItem]);
																$scope.editData[$scope.self_form_field[i]+"_txt"].push(fileList[fileItem]);
															}
														}
													}
												}
												else{
													$scope.editData[$scope.self_form_field[i]]=obj.value;
													$scope.editData[$scope.self_form_field[i]+"_txt"]=obj.realValue;
												}
												
											}
										}
										else{
											if(obj.value!=""&&obj.value!=undefined){
												if(obj.type=='messageInfo'){
													$scope.editData[obj.field]=obj.value;
													$scope.editData[obj.field+"_txt"]=obj.realValue;
													var messageList=[];
													if(obj.value!=undefined)
													{
														if(obj.value!="")
														{
															var records=JSON.parse(obj.value);
															if(records)
															{
																for(var i in records){
																	records[i].files=[];
																	if(records[i].file_list!="")
																	{
																		//console.log(records[i].file_list);
																		var list=records[i].file_list.split(',');
																		for(var f in list)
																		{
																			for(var fileItem in fileList)
																			{
																				if(fileList[fileItem].fileId==list[f])
																				{
																					records[i].files.push(fileList[fileItem]);
																				}
																			}
																		}
																	}
																	messageList.push(records[i]);
																}
															}
														}
													}
													$scope.editData[obj.field+"_list"]=messageList;
												}
												else if(obj.type=='multiupload'||obj.type=='image'||obj.type=='upload'){
													var list=obj.value.split(',');
													$scope.editData[obj.field]=[];
													$scope.editData[obj.field+"_txt"]=[];
													for(var f in list)
													{
														for(var fileItem in fileList)
														{
															if(fileList[fileItem].fileId==list[f])
															{
																if($scope.editData[obj.field]==null)
																{
																	  $scope.editData[obj.field]=[];
																}
																if($scope.editData[obj.field+"_txt"]==null)
																{
																	  $scope.editData[obj.field+"_txt"]=[];
																}
																$scope.editData[obj.field].push(fileList[fileItem]);
																$scope.editData[obj.field+"_txt"].push(fileList[fileItem]);
															}
														}
													}
												}
												else{
													$scope.editData[obj.field]=obj.value;
													$scope.editData[obj.field+"_txt"]=obj.realValue;
												}
												
											}
										}
									 }
								}
						  },
						  "finally": function () { 
							$ionicLoading.hide();
						  }
				});
						  
			},
			//流程数据情况
			openFlowStartModal:function($scope,itemid){
				$ionicLoading.show();
				$BPHttp.post({
						  "url": ApiUrl.flowProcessCreateApi,
						  "data": {
							  schemeinfoid: itemid
						  },
						  "isverify": true,
						  "success": function (redata) {
							  $scope.form_field=[];
							  $scope.self_form_field=[];
							  $scope.BillCode=[];
							  //$scope.editData = {};
							  var data=redata.status.desc;
							  data=JSON.parse(data);
							  var dataJson=data.frmContent;
							  $scope.frmEntity=data.formEntity;
							  //console.log($scope.frmEntity);
							  var FrmContent=dataJson;
							  var items="";
							  var tj=0;
							  if (data.formEntity.FrmType != 2) {
									  for (var j = 0; j < FrmContent.data.length; j++) {
										for(var count=0;count<FrmContent.data[j].fields.length;count++)
										{
											if(data.formEntity.FrmType == 0)
											{	
												$scope.form_field.push(FrmContent.data[j].fields[count].field);
												FrmContent.data[j].fields[count].selfield=FrmContent.data[j].fields[count].field;
												FrmContent.data[j].fields[count].field="f"+tj;
												$scope.self_form_field.push(FrmContent.data[j].fields[count].field);
											}
											else{
												$scope.form_field.push(FrmContent.data[j].fields[count].field);
												$scope.self_form_field.push(FrmContent.data[j].fields[count].field);
											}
											
											FrmContent.data[j].fields[count].fieldType=FrmContent.data[j].fields[count].type;
											if(FrmContent.data[j].fields[count].type=="text"||FrmContent.data[j].fields[count].type=="textarea"||FrmContent.data[j].fields[count].type=="texteditor")
											{
												if(FrmContent.data[j].fields[count].type=="text")
												{
													if(FrmContent.data[j].fields[count].control_rule=="1")
													{
														$scope.BillCode.push(FrmContent.data[j].fields[count].field);
														FrmContent.data[j].fields[count].edit=false;
													}
												}
												$scope.editData[FrmContent.data[j].fields[count].field]=FrmContent.data[j].fields[count].defaultValue;
												$scope.editData[FrmContent.data[j].fields[count].field+"_txt"]=FrmContent.data[j].fields[count].defaultValue;
											}
											if(FrmContent.data[j].fields[count].type=="datetime")
											{
												if(FrmContent.data[j].fields[count].defaultValue="Today"){
													$scope.editData[FrmContent.data[j].fields[count].field]=new Date();
												} else if(FrmContent.data[j].fields[count].defaultValue="Yesterday")
												{
													var myDate=new Date();
													myDate.setDate(myDate.getDate()-1);
													$scope.editData[FrmContent.data[j].fields[count].field]=myDate;
												} else if(FrmContent.data[j].fields[count].defaultValue="Tomorrow")
												{
													var myDate=new Date();
													myDate.setDate(myDate.getDate()+1);
													$scope.editData[FrmContent.data[j].fields[count].field]=myDate;
												}
											}
											if(FrmContent.data[j].fields[count].type=="currentInfo")
											{
												$scope.userinfo = UserInfo.get();
												//console.log($scope.userinfo);
												if(FrmContent.data[j].fields[count].infoType=="user")
												{
													$scope.editData[FrmContent.data[j].fields[count].field]=$scope.userinfo.account;
													$scope.editData[FrmContent.data[j].fields[count].field+"_txt"]=$scope.userinfo.realname;
												}
												if(FrmContent.data[j].fields[count].infoType=="department")
												{
													$scope.editData[FrmContent.data[j].fields[count].field]=$scope.userinfo.departmentid;
													$scope.editData[FrmContent.data[j].fields[count].field+"_txt"]=$scope.userinfo.departmentname;
												}
												if(FrmContent.data[j].fields[count].infoType=="organize")
												{
													$scope.editData[FrmContent.data[j].fields[count].field]=$scope.userinfo.organizeid;
													$scope.editData[FrmContent.data[j].fields[count].field+"_txt"]=$scope.userinfo.organizename;
												}
												if(FrmContent.data[j].fields[count].infoType=="date")
												{
													$scope.editData[FrmContent.data[j].fields[count].field]=$filter('date')(new Date(),'yyyy-MM-dd HH:mm:ss');
													$scope.editData[FrmContent.data[j].fields[count].field+"_txt"]=$filter('date')(new Date(),'yyyy-MM-dd HH:mm:ss');
												}
											}
											tj++;
										}
									  }
									 $scope.FrmContent=FrmContent.data;
									 items=$BPFormDesign.Preview(FrmContent.data);
								} 
								var html='<ion-modal-view>';
								html+='<ion-header-bar class="bar-stable nav-bar-block nav-title-slide-ios7">';
								html+='<button class="button button-clear" ng-click="closeEditModal()"><i class="icon ion-ios-close-empty"></i></button>';
								html+='<h1 class="title">{{editData.flow.schemecode}}/{{editData.flow.schemename}}</h1>';
								html+='<button class="button button-clear" ng-click="doSubmit()"><i class="icon ion-android-checkmark-circle"></i></button>';
								html+='</ion-header-bar>';
								html+='<ion-content>';
								html+='<ion-list class="lr-list-form">';
								html+='<div class="item item-divider">';
								html+='自定义标题 <span>*</span>';
								html+='</div>';
								html+='<ion-item class="item-input">';
								html+='<div class="lr-form-input"><i class="icon ion-ios-drag"></i>添加自定义标题</div>';
								html+='<input type = "text" ng-model="editData.CustomName" ng-class="{\'active\' : isInputActive(\'CustomName\')}" />';
								html+='</ion-item>';
								html+='<div class="item item-divider">';
								html+='重要等级 <span>*</span>';
								html+='</div>';
								html+='<ion-item ng-click="openFlowLevelModal()">';
								html+='<div class="lr-form-select" ng-hide="editData.wfleveltext != null"><i class="icon ion-ios-drag"></i>添加重要等级</div>';
								html+='<div class="item-icon-right" ng-hide="editData.wfleveltext == null">';
								html+='<div class="lr-form-label positive-bg">{{editData.wfleveltext}}</div>';
								html+='<i class="icon ion-chevron-right icon-accessory"></i>';
								html+='</div>';
								html+='</ion-item>';
								html+='<div class="item item-divider">';
								html+='发送类型 <span>*</span>';
								html+='</div>';
								html+='<ion-item ng-click="openFlowSaveModal()">';
								html+='<div class="lr-form-select" ng-hide="editData.typetext != null"><i class="icon ion-ios-drag"></i>选择发送类型</div>';
								html+='<div class="item-icon-right" ng-hide="editData.typetext == null">';
								html+='<div class="lr-form-label positive-bg">{{editData.typetext}}</div>';
								html+='<i class="icon ion-chevron-right icon-accessory"></i>';
								html+='</div>';
								html+='</ion-item>';
								
								html+='<div class="item item-divider">';
								html+='流程备注 <span>*</span>';
								html+='</div>';
								html+='<ion-item class="item-input">';
								html+='<div class="lr-form-input"><i class="icon ion-ios-drag"></i>添加流程备注</div>';
								html+='<input type = "text" ng-model="editData.Description" ng-class="{\'active\' : isInputActive(\'Description\')}" />';
								html+='</ion-item>';
								
								
								html+=items;
								
								html+='</ion-list>';
								html+='</ion-content>';
								html+='</ion-modal-view>';
								
								if($scope.BillCode.length==0){
									 var modal=$ionicModal.fromTemplate(html, {
										scope: $scope,
										animation: 'slide-left-right',
									 });
									 $scope.editModal = modal;
									 $scope.editModal.show();
									 $ionicLoading.hide();
								 }
								 else{
									 $ionicLoading.show();
									 //console.log($scope.frmEntity);
									 $BPHttp.post({
										  "url": ApiUrl.getBillCodeApi,
										  "data": { "formid": $scope.frmEntity.FrmId},
										  "success": function (data) {
												$ionicLoading.hide();
												var modal=$ionicModal.fromTemplate(html, {scope: $scope,animation: 'slide-left-right',});
												$scope.editModal = modal;
												 //数据初始化
												$scope.editModal.show();
												if(data.status.code=="0"){
													
													for(var i in $scope.BillCode)	
													{
														if(i==0) $scope.editData.CustomName=$scope.editData.CustomName+data.status.desc;
														$scope.editData[$scope.BillCode[i]]=data.status.desc;
														$scope.editData[$scope.BillCode[i]+"_txt"]=data.status.desc;
													}	
												}									
										  },
										  "error": function () {
											$BPTopAlert.show({ text: "数据获取错误" });
										  },
										  "finally": function () { 
												$ionicLoading.hide();
										  }
									 });
								 }
						},
						"finally": function () { 
							$ionicLoading.hide();
						}
				});
				
			},
			dosubmit:function($scope){
				
				  var item=$scope.FrmContent;
				  var field_list= $scope.form_field;
				  var self_field_list= $scope.self_form_field;
				  var field_array=[];
				  var Validateflag=true;
				  for (var j = 0; j < item.length; j++) {
					for(var count=0;count<item[j].fields.length;count++)
					{
						field_array.push(item[j].fields[count]);
					}
				  }
				  //console.log($scope.editData);
				  
				  for(var j=0;j<field_array.length; j++)
				  {
					  var field_id=field_array[j].field;
					  
					  
					  if(field_array[j].fieldType=="datetime")
					  {
						  if(field_array[j].dateformat == "date")
						  {
							$scope.editData[field_id]=$BPFormatDate($scope.editData[field_id], "yyyy-MM-dd");
						  }
						  else
						  {
							$scope.editData[field_id]=$BPFormatDate($scope.editData[field_id], "yyyy-MM-dd hh:mm");
						  }
					  }
					  if(field_array[j].fieldType=='multiupload'||field_array[j].fieldType=='image'||field_array[j].fieldType=='upload')
					  {
						  var file_list="";
						  for(var i in $scope.editData[field_id])
						  {
							  if(file_list!="")file_list+=",";
							  file_list+=$scope.editData[field_id][i].fileId;
						  }
						  $scope.editData[field_id+"_listxx_Content"]=file_list;
						  //$scope.editData[field_id]=file_list;
						  //$scope.editData[field_id+"_txt"]=file_list;
					  }
					  field_array[j].value=$scope.editData[field_id];
					  if($scope.editData[field_id+"_listxx_Content"]!=""&&$scope.editData[field_id+"_listxx_Content"]!=undefined){
						  field_array[j].realValue=$scope.editData[field_id+"_listxx_Content"];
						  field_array[j].value=$scope.editData[field_id+"_listxx_Content"]; 
					  }
					  else if($scope.editData[field_id+"_txt"]!=""&&$scope.editData[field_id+"_txt"]!=undefined){
						field_array[j].realValue=$scope.editData[field_id+"_txt"];
					  }
					  else
						field_array[j].realValue=$scope.editData[field_id];  
					  if(field_array[j].verify!="")
					  {
						  var ops={};
						  
						  ops.value=field_array[j].value;
						  ops.checkexpession=field_array[j].verify;
						  ops.errormsg=field_array[j].label;
						  
						  Validateflag=$BPValidform(ops);
						  if(Validateflag==false)
							  break;
					  }
				  }
				  
				  if(Validateflag!=false)
				  {
					 if($scope.BillCode.length>0){
						 $BPHttp.post({
							  "url": ApiUrl.getBillCodeApi,
							  "data": { "formid": $scope.frmEntity.FrmId},
							  "success": function (data) {
									$ionicLoading.hide();
									if(data.status.code=="0"){
										
										for(var i in $scope.BillCode)	
										{
											if(i==0) $scope.editData.CustomName=$scope.editData.CustomName+data.status.desc;
											$scope.editData[$scope.BillCode[i]]=data.status.desc;
											$scope.editData[$scope.BillCode[i]+"_txt"]=data.status.desc;
										}
										sendDataInit($scope,item,field_list,self_field_list,field_array,Validateflag);
									}									
							  },
							  "error": function () {
								$BPTopAlert.show({ text: "数据获取错误" });
							  },
							  "finally": function () { 
									$ionicLoading.hide();
							  }
						 });
					 }
					 else{
						 sendDataInit($scope,item,field_list,self_field_list,field_array,Validateflag);
					 }
				  }
			}
		}
   }])
  //数据表单解析  show dosubmit
  .factory('$BPFormMethod', ['$BPPopup','$base64','$filter','$BPHttp','$BPTopAlert','$rootScope','$base64','UserInfo','$ionicModal','$BPFormDesign','$BPSelectModal','$AreaInfo','$BPUserSelectModal','$BaseInfo','$OrgInfo','$ionicModal','$cordovaActionSheet','$SelectPicture','$BPGetDataItem','$BPCheckboxModal','$BPGetDataTable','$ionicLoading','ApiUrl','$BPValidform','$BPFormatDate','$BPSendData','$timeout','$BPMessagePageModal',
  function($BPPopup,$base64,$filter,$BPHttp,$BPTopAlert,$rootScope, $base64,UserInfo,$ionicModal,$BPFormDesign,$BPSelectModal,$AreaInfo,$BPUserSelectModal,$BaseInfo,$OrgInfo,$ionicModal,$cordovaActionSheet,$SelectPicture,$BPGetDataItem,$BPCheckboxModal,$BPGetDataTable,$ionicLoading,ApiUrl,$BPValidform,$BPFormatDate,$BPSendData,$timeout,$BPMessagePageModal) {
		$BaseInfo.init();//初始化基础信息
		$AreaInfo.init();//初始化区域列表
		$OrgInfo.init();//初始化组织架构信息
		
		function sendDataInit($scope,item,field_list,self_field_list,field_array,Validateflag,ItemID)
		{
			if(Validateflag!=false)
			{
					 
					  var formData = "";
					  var isneedCheck = 0;

					  for(var j=0;j<field_array.length; j++)
					  {
						  if(field_array[j].control_uniq==1)
						  {
							  //console.log(field_array[j]);
							  if(formData!="")formData+=",";
							  isneedCheck=1;
							  if(field_array[j].selfield)
								formData += '{"FrmID":"' + $scope.frmEntity.frmId + '","FieldID":"' + field_array[j].selfield + '","ID":"' + field_array[j].id + '","Data":"' + field_array[j].realValue + '","control_uniq_msg":"'+field_array[j].control_uniqmsg+'"}';
							  else
								formData += '{"FrmID":"' + $scope.frmEntity.frmId + '","FieldID":"' + field_array[j].field + '","ID":"' + field_array[j].id + '","Data":"' + field_array[j].realValue + '","control_uniq_msg":"'+field_array[j].control_uniqmsg+'"}';  

						  }
					  }
					  if (ItemID!=""){
						isneedCheck=0;
					  }
					  if (isneedCheck == 0)
					  {
						//console.log(field_array);
						$BPSendData.send_data($scope,ItemID,field_array);
					  }
					  else if (isneedCheck == 1) {
						formData = "[" + formData + "]";
						//console.log(formData);
						$ionicLoading.show();
						$BPHttp.post({
							  "url": ApiUrl.getUniqueCode,
							  "data": { "formData": formData},
							  "success": function (data) {
									$ionicLoading.hide();
									var formDataList=[];
									formDataList=JSON.parse(formData);
									if(data.status.desc!= ""){
										var fields = data.status.desc.split(',');
										for (var i = 0; i < fields.length; i++) {
											var msg="";
											for(var j in formDataList)
											{
												if(formDataList[j].ID==fields[i])
												{
													msg=formDataList[j].control_uniq_msg;
													break;
												}
											}
											$BPTopAlert.show({ text: msg });
											break;
										}

									}
									else{
										//console.log(field_array);
										$BPSendData.send_data($scope,ItemID,field_array);
									}
							  },
							  "error": function () {
								$BPTopAlert.show({ text: "数据获取错误" });
							  },
							  "finally": function () { 
									$ionicLoading.hide();
							  }
						 });
						  
					  }					  
			}
		}
		
		return {
			//流程数据情况
			openFlowDetailsModal:function($scope,frmJson,title,itemid){
				$ionicLoading.show();
				$BPHttp.post({
						  "url": ApiUrl.getProcessJsonApi,
						  "data": { "keyValue": itemid},
						  "success": function (data) {
								//$ionicLoading.hide();
								$scope.form_field=[];
								$scope.self_form_field=[];
								$scope.editData = {};
								data=data.result;
								var processScheme=data.processScheme.schemeContent;
								
								var SchemeContentObj=JSON.parse(processScheme);
								
								var schemeContent = JSON.parse(SchemeContentObj.SchemeContent);
								$scope.SchemeContentObj=schemeContent;

								//console.log(data);
								if (data.schemeInfo.formList != "") {
									var dlist = data.schemeInfo.formList.split(',');
									for (var d in dlist) {
										var done = dlist[d];
										$ionicLoading.show();
										$BPHttp.post({
										  "url": ApiUrl.getFormEntityJsonApi,
										  "data": { "keyValue": done},
										  "success": function (formdata) {
													var items="";
													var tj=0;
													var FrmContent=JSON.parse(formdata.result.frmContent);
													if (FrmContent.type != 2) {
														  for (var j = 0; j < FrmContent.data.length; j++) {
															for(var count=0;count<FrmContent.data[j].fields.length;count++)
															{
																if(FrmContent.type == 0)
																{	
																	$scope.form_field.push(FrmContent.data[j].fields[count].field);
																	FrmContent.data[j].fields[count].selfield=FrmContent.data[j].fields[count].field;
																	FrmContent.data[j].fields[count].field="f"+tj;
																	$scope.self_form_field.push(FrmContent.data[j].fields[count].field);
																}
																else{
																	$scope.form_field.push(FrmContent.data[j].fields[count].field);
																	$scope.self_form_field.push(FrmContent.data[j].fields[count].field);
																}
																FrmContent.data[j].fields[count].isdel=0;
																FrmContent.data[j].fields[count].edit=false;
																FrmContent.data[j].fields[count].fieldType=FrmContent.data[j].fields[count].type;
																tj++;
															}
														  }
														 items=$BPFormDesign.Preview(FrmContent.data);
													}
													//初始化数据
													 var html='<ion-modal-view>';
													 html+='<ion-header-bar class="bar-stable nav-bar-block nav-title-slide-ios7">';
													 html+='<button class="button button-clear" ng-click="closeDetailsModal()"><i class="icon ion-ios-close-empty"></i></button>';
													 html+='<h1 class="title">'+title+'</h1>';
													 html+='<button class="button button-clear" ng-click="openFlowRptModal(\''+itemid+'\')">轨迹</button>';
													 html+='</ion-header-bar>';
													 html+='<ion-content>';
													 html+='<ion-list class="lr-list-form">';
													 html+=items;
													 html+='</ion-list>';
													 html+='</ion-content>';
													 html+='</ion-modal-view>';
													 var modal=$ionicModal.fromTemplate(html, {scope: $scope,animation: 'slide-in-up',});
													 $scope.editModal = modal;
													 //数据初始化
													 $scope.editModal.show();
													 var selftdata=JSON.parse(JSON.parse(data.processScheme.schemeContent).frmData);
													 var fileList=JSON.parse(data.fileList);
													 for(var i in selftdata)
													 {
														var obj=selftdata[i];
														
														if(FrmContent.type == 0)
														{
															var i=$scope.form_field.indexOf(obj.field);
															
															if(obj.value!=""&&obj.value!=undefined){
																if(obj.type=='messageInfo'){
																	$scope.editData[$scope.self_form_field[i]]=obj.value;
																	$scope.editData[$scope.self_form_field[i]+"_txt"]=obj.realValue;
																	var messageList=[];
																	if(obj.value!=undefined)
																	{
																		if(obj.value!="")
																		{
																			var records=JSON.parse(obj.value);
																			if(records)
																			{
																				for(var i in records){
																					records[i].files=[];
																					if(records[i].file_list!="")
																					{
																						//console.log(records[i].file_list);
																						var list=records[i].file_list.split(',');
																						for(var f in list)
																						{
																							for(var fileItem in fileList)
																							{
																								if(fileList[fileItem].fileId==list[f])
																								{
																									records[i].files.push(fileList[fileItem]);
																								}
																							}
																						}
																					}
																					messageList.push(records[i]);
																				}
																			}
																		}
																	}
																	$scope.editData[$scope.self_form_field[i]+"_list"]=messageList;
																}
																else if(obj.type=='multiupload'||obj.type=='image'||obj.type=='upload'){
																	var list=obj.value.split(',');
																	$scope.editData[$scope.self_form_field[i]]=[];
																	$scope.editData[$scope.self_form_field[i]+"_txt"]=[];
																	for(var f in list)
																	{
																		for(var fileItem in fileList)
																		{
																			if(fileList[fileItem].fileId==list[f])
																			{
																				if($scope.editData[$scope.self_form_field[i]]==null)
																				{
																					  $scope.editData[$scope.self_form_field[i]]=[];
																				}
																				if($scope.editData[$scope.self_form_field[i]+"_txt"]==null)
																				{
																					  $scope.editData[$scope.self_form_field[i]+"_txt"]=[];
																				}
																				$scope.editData[$scope.self_form_field[i]].push(fileList[fileItem]);
																				$scope.editData[$scope.self_form_field[i]+"_txt"].push(fileList[fileItem]);
																			}
																		}
																	}
																}
																else{
																	$scope.editData[$scope.self_form_field[i]]=obj.value;
																	$scope.editData[$scope.self_form_field[i]+"_txt"]=obj.realValue;
																}
																
															}
														}
														else{
															if(obj.value!=""&&obj.value!=undefined){
																if(obj.type=='messageInfo'){
																	$scope.editData[obj.field]=obj.value;
																	$scope.editData[obj.field+"_txt"]=obj.realValue;
																	
																	var messageList=[];
																	if(obj.value!=undefined)
																	{
																		if(obj.value!="")
																		{
																			var records=JSON.parse(obj.value);
																			if(records)
																			{
																				for(var i in records){
																					records[i].files=[];
																					if(records[i].file_list!="")
																					{
																						//console.log(records[i].file_list);
																						var list=records[i].file_list.split(',');
																						for(var f in list)
																						{
																							for(var fileItem in fileList)
																							{
																								if(fileList[fileItem].fileId==list[f])
																								{
																									records[i].files.push(fileList[fileItem]);
																								}
																							}
																						}
																					}
																					messageList.push(records[i]);
																				}
																			}
																		}
																	}
																	$scope.editData[obj.field+"_list"]=messageList;
																}
																else if(obj.type=='multiupload'||obj.type=='image'||obj.type=='upload'){
																	var list=obj.value.split(',');
																	$scope.editData[obj.field]=[];
																	$scope.editData[obj.field+"_txt"]=[];
																	for(var f in list)
																	{
																		for(var fileItem in fileList)
																		{
																			if(fileList[fileItem].fileId==list[f])
																			{
																				if($scope.editData[obj.field]==null)
																				{
																					  $scope.editData[obj.field]=[];
																				}
																				if($scope.editData[obj.field+"_txt"]==null)
																				{
																					  $scope.editData[obj.field+"_txt"]=[];
																				}
																				$scope.editData[obj.field].push(fileList[fileItem]);
																				$scope.editData[obj.field+"_txt"].push(fileList[fileItem]);
																			}
																		}
																	}
																}
																else{
																	$scope.editData[obj.field]=obj.value;
																	$scope.editData[obj.field+"_txt"]=obj.realValue;
																}
																
															}
														}
													 }
										  },
										  "error": function () {
											$BPTopAlert.show({ text: "数据获取错误" });
										  },
										  "finally": function () { 
											$ionicLoading.hide();
										  }
										});
									}
								}

						  },
						  "error": function () {
							$ionicLoading.hide();
							$BPTopAlert.show({ text: "数据获取错误" });
						  }
					 });
			},
			//表单数据情况
			openDetailsModal:function($scope,frmJson,title,itemid){
				  var FrmContent=JSON.parse($scope.frmEntity.frmContent);
				  $scope.form_field=[];
				  $scope.self_form_field=[];
				  $scope.editData = {};
				  var items="";
				  var tj=0;
				  if (FrmContent.type != 2) {
					  for (var j = 0; j < FrmContent.data.length; j++) {
						for(var count=0;count<FrmContent.data[j].fields.length;count++)
						{
							if(frmJson.type == 0)
							{	
								$scope.form_field.push(FrmContent.data[j].fields[count].field);
								FrmContent.data[j].fields[count].selfield=FrmContent.data[j].fields[count].field;
								FrmContent.data[j].fields[count].field="f"+tj;
								$scope.self_form_field.push(FrmContent.data[j].fields[count].field);
							}
							else{
								$scope.form_field.push(FrmContent.data[j].fields[count].field);
								$scope.self_form_field.push(FrmContent.data[j].fields[count].field);
							}
							FrmContent.data[j].fields[count].isdel=0;
							FrmContent.data[j].fields[count].edit=false;
							FrmContent.data[j].fields[count].fieldType=FrmContent.data[j].fields[count].type;
							
							tj++;
						}
					  }
					 items=$BPFormDesign.Preview(FrmContent.data);
				 }
				 var html='<ion-modal-view>';
				 html+='<ion-header-bar class="bar-stable nav-bar-block nav-title-slide-ios7">';
				 html+='<button class="button button-clear" ng-click="closeDetailsModal()"><i class="icon ion-ios-close-empty"></i></button>';
				 html+='<h1 class="title">'+title+'</h1>';
				 html+='<button class="button button-clear" ng-click="closeDetailsModal();openEditModal(\''+itemid+'\')"><i class="icon ion-ios-compose-outline"></i></button>';
				 html+='</ion-header-bar>';
				 html+='<ion-content>';
				 html+='<ion-list class="lr-list-form">';
				 html+=items;
				 html+='</ion-list>';
				 html+='</ion-content>';
				 html+='</ion-modal-view>';
				 
				 $BPSendData.init_data($scope,true,frmJson,itemid,html);
			},
			openEditModal:function($scope,frmJson,title,itemid) {
				  var FrmContent=JSON.parse($scope.frmEntity.frmContent);
				  $scope.form_field=[];
				  $scope.BillCode=[];
				  $scope.self_form_field=[];
				  $scope.editData = {};
				  $scope.itemid=itemid;
				  var items="";
				  var tj=0;
				  
				  if (FrmContent.type != 2) {
					  for (var j = 0; j < FrmContent.data.length; j++) {
						for(var count=0;count<FrmContent.data[j].fields.length;count++)
						{
							if(frmJson.type == 0)
							{	
								$scope.form_field.push(FrmContent.data[j].fields[count].field);
								FrmContent.data[j].fields[count].selfield=FrmContent.data[j].fields[count].field;
								FrmContent.data[j].fields[count].field="f"+tj;
								$scope.self_form_field.push(FrmContent.data[j].fields[count].field);
							}
							else{
								$scope.form_field.push(FrmContent.data[j].fields[count].field);
								$scope.self_form_field.push(FrmContent.data[j].fields[count].field);
							}
							FrmContent.data[j].fields[count].isdel=0;
							FrmContent.data[j].fields[count].edit=true;
							FrmContent.data[j].fields[count].fieldType=FrmContent.data[j].fields[count].type;
							if(FrmContent.data[j].fields[count].type=="text"||FrmContent.data[j].fields[count].type=="textarea"||FrmContent.data[j].fields[count].type=="texteditor")
							{
								if(FrmContent.data[j].fields[count].type=="text")
								{
									if(FrmContent.data[j].fields[count].control_rule=="1")
									{
										$scope.BillCode.push(FrmContent.data[j].fields[count].field);
										FrmContent.data[j].fields[count].edit=false;
									}
								}
								$scope.editData[FrmContent.data[j].fields[count].field]=FrmContent.data[j].fields[count].defaultValue;
								$scope.editData[FrmContent.data[j].fields[count].field+"_txt"]=FrmContent.data[j].fields[count].defaultValue;
							}
							if(FrmContent.data[j].fields[count].type=="datetime")
							{
								if(FrmContent.data[j].fields[count].defaultValue="Today"){
									$scope.editData[FrmContent.data[j].fields[count].field]=new Date();
								} else if(FrmContent.data[j].fields[count].defaultValue="Yesterday")
								{
									var myDate=new Date();
									myDate.setDate(myDate.getDate()-1);
									$scope.editData[FrmContent.data[j].fields[count].field]=myDate;
								} else if(FrmContent.data[j].fields[count].defaultValue="Tomorrow")
								{
									var myDate=new Date();
									myDate.setDate(myDate.getDate()+1);
									$scope.editData[FrmContent.data[j].fields[count].field]=myDate;
								}
							}
							if(FrmContent.data[j].fields[count].type=="currentInfo")
							{
								$scope.userinfo = UserInfo.get();
								//console.log($scope.userinfo);
								if(FrmContent.data[j].fields[count].infoType=="user")
								{
									$scope.editData[FrmContent.data[j].fields[count].field]=$scope.userinfo.account;
									$scope.editData[FrmContent.data[j].fields[count].field+"_txt"]=$scope.userinfo.realname;
								}
								if(FrmContent.data[j].fields[count].infoType=="department")
								{
									$scope.editData[FrmContent.data[j].fields[count].field]=$scope.userinfo.departmentid;
									$scope.editData[FrmContent.data[j].fields[count].field+"_txt"]=$scope.userinfo.departmentname;
								}
								if(FrmContent.data[j].fields[count].infoType=="organize")
								{
									$scope.editData[FrmContent.data[j].fields[count].field]=$scope.userinfo.organizeid;
									$scope.editData[FrmContent.data[j].fields[count].field+"_txt"]=$scope.userinfo.organizename;
								}
								if(FrmContent.data[j].fields[count].infoType=="date")
								{
									$scope.editData[FrmContent.data[j].fields[count].field]=$filter('date')(new Date(),'yyyy-MM-dd HH:mm:ss');
									$scope.editData[FrmContent.data[j].fields[count].field+"_txt"]=$filter('date')(new Date(),'yyyy-MM-dd HH:mm:ss');
								}
								
								
							}
							
							
							tj++;
						}
					  }
					 $scope.FrmContent=FrmContent.data;
					 items=$BPFormDesign.Preview(FrmContent.data);
				 } 
				 var html='<ion-modal-view>';
				 html+='<ion-header-bar class="bar-stable nav-bar-block nav-title-slide-ios7">';
				 html+='<button class="button button-clear" ng-click="closeEditModal()"><i class="icon ion-ios-close-empty"></i></button>';
				 html+='<h1 class="title">'+title+'</h1>';
				 html+='<button class="button button-clear" ng-click="doSubmit(\''+itemid+'\')"><i class="icon ion-android-checkmark-circle"></i></button>';
				 html+='</ion-header-bar>';
				 html+='<ion-content>';
				 html+='<ion-list class="lr-list-form">';
				 html+=items;
				 html+='</ion-list>';
				 html+='</ion-content>';
				 html+='</ion-modal-view>';
				 				 
				 
				 if(itemid!="")
				 {
					 $scope.BillCode=[];
					 $BPSendData.init_data($scope,true,frmJson,itemid,html);
				 }else{
					 if($scope.BillCode.length==0){
						 var modal=$ionicModal.fromTemplate(html, {scope: $scope,animation: 'slide-in-up',});
						 $scope.editModal = modal;
						 $scope.editModal.show();
					 }
					 else{
						 $ionicLoading.show();
						 
						 $BPHttp.post({
							  "url": ApiUrl.getBillCodeApi,
							  "data": { "formid": $scope.frmEntity.frmId},
							  "success": function (data) {
									$ionicLoading.hide();
									var modal=$ionicModal.fromTemplate(html, {scope: $scope,animation: 'slide-in-up',});
									$scope.editModal = modal;
									 //数据初始化
									$scope.editModal.show();
									if(data.status.code=="0"){
										for(var i in $scope.BillCode)	
										{
											$scope.editData[$scope.BillCode[i]]=data.status.desc;
											$scope.editData[$scope.BillCode[i]+"_txt"]=data.status.desc;
										}	
									}									
							  },
							  "error": function () {
								$BPTopAlert.show({ text: "数据获取错误" });
							  },
							  "finally": function () { 
									$ionicLoading.hide();
							  }
						 });
					 }
					 //数据初始化
				 }
			},
			openCrmSelectModal:function($scope,title,field)
			{
				$ionicLoading.show();
				$BPHttp.post({
                  "url": ApiUrl.getCrmListApi,
                  "isverify": true,
                  "success": function (data) {
                      $scope.RadioSideList = JSON.parse(data.status.desc);
					  $BPSelectModal({title:title,bgAllColor:"positive-bg",selectValue:$scope.editData[field],text:"client_name",value:"id",data:$scope.RadioSideList,
						onChange: function (item) {
						  $scope.editData[field] = item.value;
						  $scope.editData[field+'_txt'] = item.text;
						  //根据选择初始化数据
						  var tag_id=item.value;
						  var frmJson={type:1};
						  //console.log(item);
						  $BPSendData.init_data($scope,false,frmJson,tag_id,"");
						}
					  });
                  },
				  "finally": function () { 
						$ionicLoading.hide();
				  }
				});
			},
			openAreaSelectModal:function($scope,dataType,field){
				
				if(dataType=='first'){
					$scope.RadioSideList=$AreaInfo.getProvinceData();
					$BPSelectModal({title:"选择省份",bgAllColor:"positive-bg",selectValue:$scope.editData[field],text:"name",value:"id",data:$scope.RadioSideList,
						onClick: function (item) {
						  $scope.editData[field] = item.value;
						  $scope.editData[field+'_txt'] = item.text;
						}
					});
				} else if(dataType=='secord'){
					var selectValue=[];
					var selectValue_1="";
					var selectValue_2="";
					if($scope.editData[field]!=null) selectValue=$scope.editData[field].split(',');
					if(selectValue.length>0) selectValue_1=selectValue[0];
					if(selectValue.length>1) selectValue_2=selectValue[1];
					$scope.RadioSideList=$AreaInfo.getProvinceData();
					$BPSelectModal({title:"选择省份",bgAllColor:"positive-bg",selectValue:selectValue_1,text:"name",value:"id",data:$scope.RadioSideList,
						onClick: function (item) {
						  $scope.editData[field] = item.value;
						  $scope.editData[field+'_txt'] = item.text;
						  $scope.RadioSideList=$AreaInfo.getCityData(item.value);
						      $BPSelectModal({title:"选择城市",bgAllColor:"positive-bg",selectValue:selectValue_2,text:"name",value:"id",data:$scope.RadioSideList,
									onClick: function (item) {
									  $scope.editData[field] +=','+item.value;
									  $scope.editData[field+'_txt'] +=','+item.text;
									}
							  });						  
						}
					});
				} else{
					
					var selectValue=[];
					var selectValue_1="";
					var selectValue_2="";
					var selectValue_3="";
					var thisP="";
					if($scope.editData[field]!=null) selectValue=$scope.editData[field].split(',');
					if(selectValue.length>0) selectValue_1=selectValue[0];
					if(selectValue.length>1) selectValue_2=selectValue[1];
					if(selectValue.length>2) selectValue_3=selectValue[2];
					$scope.RadioSideList=$AreaInfo.getProvinceData();
					$BPSelectModal({title:"选择省份",bgAllColor:"positive-bg",selectValue:selectValue_1,text:"name",value:"id",data:$scope.RadioSideList,
						onClick: function (item) {
						  thisP=item.value;
						  $scope.editData[field] = item.value;
						  $scope.editData[field+'_txt'] = item.text;
						  $scope.RadioSideList=$AreaInfo.getCityData(item.value);
						  $BPSelectModal({title:"选择城市",bgAllColor:"positive-bg",selectValue:selectValue_2,text:"name",value:"id",data:$scope.RadioSideList,
								onClick: function (item) {
								  $scope.editData[field] +=','+item.value;
								  $scope.editData[field+'_txt'] +=','+item.text;
								  $scope.RadioSideList=$AreaInfo.getAreaData(thisP,item.value);
								  $BPSelectModal({title:"选择城市",bgAllColor:"positive-bg",selectValue:selectValue_3,text:"name",value:"id",data:$scope.RadioSideList,
										onClick: function (item) {
										  $scope.editData[field] +=','+item.value;
										  $scope.editData[field+'_txt'] +=','+item.text;
										}
								 });	
								  
								}
						  });								  
						}
					});
				}
			},
			openBaseSelectModal:function($scope,dataType,field){
				if(dataType=='user')
				{
					$scope.RadioSideList=$BaseInfo.getDepartmentUserInfo();
					$BPUserSelectModal({title:"选择用户",bgAllColor:"positive-bg",selectValue:$scope.editData[field],data:$scope.RadioSideList,
						onChange: function (item) {
						  $scope.editData[field] = item.userId;
						  $scope.editData[field+'_txt'] = item.realName;
						}
					 });
					 
				}
				if(dataType=='department')
				{
					$scope.RadioSideList=$OrgInfo.getDepartmentListInfo();
					$BPSelectModal({title:"选择部门",bgAllColor:"positive-bg",selectValue:$scope.editData[field],text:"fullName",value:"departmentId",data:$scope.RadioSideList,
						onChange: function (item) {
						  $scope.editData[field] = item.value;
						  $scope.editData[field+'_txt'] = item.text;
						}
					 });
					 
				}
				if(dataType=='organize')
				{
					$scope.RadioSideList=$OrgInfo.getOrganizeListInfo();
					$BPSelectModal({title:"选择公司",bgAllColor:"positive-bg",selectValue:$scope.editData[field],text:"fullName",value:"organizeId",data:$scope.RadioSideList,
						onChange: function (item) {
						  $scope.editData[field] = item.value;
						  $scope.editData[field+'_txt'] = item.text;
						}
					 });
					 $ionicLoading.hide();
				}
				if(dataType=='post')
				{
					$scope.RadioSideList=$OrgInfo.getPostListInfo();
					$BPSelectModal({title:"选择职务",bgAllColor:"positive-bg",selectValue:$scope.editData[field],text:"fullName",value:"roleId",data:$scope.RadioSideList,
						onChange: function (item) {
						  $scope.editData[field] = item.value;
						  $scope.editData[field+'_txt'] = item.text;
						}
					 });
					 
				}
				if(dataType=='job')
				{
					$scope.RadioSideList=$OrgInfo.getJobListInfo();
					$BPSelectModal({title:"选择岗位",bgAllColor:"positive-bg",selectValue:$scope.editData[field],text:"fullName",value:"roleId",data:$scope.RadioSideList,
						onChange: function (item) {
						  $scope.editData[field] = item.value;
						  $scope.editData[field+'_txt'] = item.text;
						}
					 });
					 $ionicLoading.hide();
				}
				if(dataType=='role')
				{
					$scope.RadioSideList=$OrgInfo.getRoleListInfo();
					$BPSelectModal({title:"选择角色",bgAllColor:"positive-bg",selectValue:$scope.editData[field],text:"fullName",value:"roleId",data:$scope.RadioSideList,
						onChange: function (item) {
						  $scope.editData[field] = item.value;
						  $scope.editData[field+'_txt'] = item.text;
						}
					 });
					 
				}
			},
			getFileContents:function($scope,file){
					//如果是图片文件就直接浏览
					var url=file.fileurl;
					url=url.replace('~/','/');
					url=ApiUrl.webRoot+url;
					if(file.filetype=='jpg'||file.filetype=='png'||file.filetype=='gif'||file.filetype=='bmp'||file.filetype=='jpge'){
						$scope.showImageModal(url);
					}
					//如果是其他文件就下载
					else{
						var url = pathurl;
						window.open(url, '_system', 'location=no');
					}
			},
			showImageModal:function($scope,url){
					var html='<div class="modal image-modal transparent" ng-click="closeImageModal()">';
						//html+='<ion-slide-box on-slide-changed="slideChanged(index)" show-pager="true" active-slide="activeSlide">';
						html+='		<img ng-src="'+url+'" class="fullscreen-image"/>';
						//html+='</ion-slide-box>';
						html+='</div>';
					
					var modal=$ionicModal.fromTemplate(html, {scope: $scope,animation: 'slide-in-up',});
					$scope.ImageModal = modal;
					$scope.ImageModal.show();
					$scope.closeImageModal=function(){
						$scope.ImageModal.remove();
					}
			},
			doDeleteFileMessage:function($scope,file,listitem,field){
				//信息记录 删除文件
				if(listitem!=null&&file!=null)
				{
					//console.log(listitem);
					var itemList=[];
					var listitem_update={data_id:listitem.data_id,date_value:listitem.date_value,file_list:"",userid_realvalue:listitem.userid_realvalue,userid_value:listitem.userid_value};
					listitem_update.files=[];
					listitem_update.file_list="";
					//删除file_list信息
					var fileArray=listitem.file_list.split(',');
					
					for(var f in fileArray)
					{
						if(file.fileId!=fileArray[f])
						{
							if(listitem_update.file_list!="") listitem_update.file_list+=",";
							listitem_update.file_list+=fileArray[f];
						}
					}
					//删除对象集 files
					for(var i in listitem.files)
					{
						if(listitem.files[i].fileId!=file.fileId){
							listitem_update.files.push(listitem.files[i]);
						}
					}
					
					for(var i in $scope.editData[field+"_list"])
					{
						if($scope.editData[field+"_list"][i].data_id!=listitem.data_id)
						{
							itemList.push($scope.editData[field+"_list"][i]);
						}
						else{
							itemList.push(listitem_update);
						}
					}
					$scope.editData[field+"_list"]=itemList;
					var valueArray=[];
					for(var tar in itemList){
						valueArray.push({
							data_id:itemList[tar].data_id,
							date_value:itemList[tar].date_value,
							file_list:itemList[tar].file_list,
							userid_value:itemList[tar].userid_value,
							userid_realvalue:itemList[tar].userid_realvalue
						});
					}
					$scope.editData[field+"_txt"]=JSON.stringify(valueArray);
					$scope.editData[field]=JSON.stringify(valueArray);
				}
				
			},
			openMessageSelectModal:function($scope,fieldType,field,infoType,listitem,lablename){
				console.log($scope.editData[field+"_list"]);
				var selectItem=null;
				if(listitem!=null){
					selectItem={
						data_id:listitem.data_id,
						date_value:listitem.date_value,
						file_list:listitem.file_list,
						files:listitem.files,
						userid_realvalue:listitem.userid_realvalue,
						userid_value:listitem.userid_value,
					};
				}
				$BPMessagePageModal({listitem:selectItem,lablename:lablename,
						onChange: function (itemData) {
							//console.log(itemData);
							//console.log(field);
							
							if(itemData.files!=null)
							{
								if(itemData.files.length>0)
								{
									var file_list="";
									for(var file in itemData.files)
									{
										if(file_list!="") file_list+=",";
										file_list+=itemData.files[file].fileId;
									}
									itemData.file_list=file_list;
								}
							}
							
						    var itemList=[];
							if(selectItem!=null){
								for(var sj in $scope.editData[field+"_list"])
								{
									if($scope.editData[field+"_list"][sj].data_id!=itemData.data_id)
									{
										//console.log($scope.editData[field][i]);
										itemList.push($scope.editData[field+"_list"][sj]);
									}
									else{
										//console.log(itemData);
										itemList.push(itemData);
									}
								}
								
								$scope.editData[field+"_list"]=itemList;
							}
							else{
								if($scope.editData[field+"_list"]==null||$scope.editData[field+"_list"]==undefined)
								{
									$scope.editData[field+"_list"]=[];
								}
								$scope.editData[field+"_list"].push(itemData);
							}
							console.log($scope.editData[field+"_list"]);
							var valueArray=[];
							for(var tar in $scope.editData[field+"_list"]){
								valueArray.push({
									data_id:$scope.editData[field+"_list"][tar].data_id,
									date_value:$scope.editData[field+"_list"][tar].date_value,
									file_list:$scope.editData[field+"_list"][tar].file_list,
									userid_value:$scope.editData[field+"_list"][tar].userid_value,
									userid_realvalue:$scope.editData[field+"_list"][tar].userid_realvalue
								});
							}
							console.log(valueArray);
							$scope.editData[field+"_txt"]=JSON.stringify(valueArray);
							$scope.editData[field]=JSON.stringify(valueArray);
							console.log($scope.editData[field+"_list"]);
							console.log($scope.editData[field+"_txt"]);
							console.log($scope.editData[field]);
						}
				});
			},
			doDeleteMessage:function($scope,listitem,field){
				//信息记录 删除文件
				if(listitem!=null)
				{
					var itemList=[];
					for(var i in $scope.editData[field+"_list"])
					{
						if($scope.editData[field+"_list"][i]!=listitem)
						{
							itemList.push($scope.editData[field+"_list"][i]);
						}
					}
					$scope.editData[field+"_list"]=itemList;
					var valueArray=[];
					for(var tar in itemList){
						valueArray.push({
							data_id:itemList[tar].data_id,
							date_value:itemList[tar].date_value,
							file_list:itemList[tar].file_list,
							userid_value:itemList[tar].userid_value,
							userid_realvalue:itemList[tar].userid_realvalue
						});
					}
					$scope.editData[field+"_txt"]=JSON.stringify(valueArray);
					$scope.editData[field]=JSON.stringify(valueArray);
				}
			},
			doDeleteFile:function($scope,file,field){
			    var itemList=[];
				for(var i in $scope.editData[field])
				{
					if($scope.editData[field][i]!=file)
					{
						itemList.push($scope.editData[field][i]);
					}
				}
				$scope.editData[field]=itemList;
			},
			openFileSelectModal:function($scope,type,field)
			{
				var options = {
					title: '请选择',
					buttonLabels: ['相机', '图库'],
					addCancelButtonWithLabel: '取消',
					androidEnableCancelButton: true,
					winphoneEnableCancelButton: true
				};
				document.addEventListener("deviceready", function() {
					$cordovaActionSheet.show(options)
						.then(function(btnIndex) {
							var index = btnIndex;
							
							switch (index){  
							   case 1:
								 $SelectPicture.chooseSinglePicture({
									 "width":100,
									 "height":100,
									 "success":function (data) {
										  if($scope.editData[field]==null)
										  {
											  $scope.editData[field]=[];
										  }
										  $scope.editData[field].push(data);
										  //console.log($scope.editData[field]);
									  }
								 });	
								 break;  
							   case 2:
								 $SelectPicture.choosePictures({
									 "success": function (data) {
										  if($scope.editData[field]==null)
										  {
											  $scope.editData[field]=[];
										  }
										  $scope.editData[field].push(data);
										  //console.log($scope.editData[field]);
									  }
								 });						   
								 break;  
							   default:  
									break;  
							}      
						});
				}, false);
			},
			openRadioModal:function($scope,dataSource,defaultValue,title,field,dataItemCode,dbId,dbTable,dbFiledValue,dbFiledText){
					$ionicLoading.show();
					if(dataSource=="dataItem")
					{
						$BPGetDataItem({
								"itemName": dataItemCode,
								"callback": function (data) {
									$scope.RadioSideList = data;
									$ionicLoading.hide();
									$BPSelectModal({
										title:title,
										bgAllColor:"positive-bg",
										selectValue:$scope.editData[field],
										text:"itemName",
										value:"itemValue",
										data:$scope.RadioSideList,
										onChange: function (item) {
										  $scope.editData[field] = item.value;
										  $scope.editData[field+'_txt'] = item.text;
										}
									  });
								},
								"finally": function () { 
									$ionicLoading.hide();
								}
						});
					}
					else{
						$BPGetDataTable({
								"dbId": dbId,
								"dbTable": dbTable,
								"dbFiledValue": dbFiledValue,
								"dbFiledText": dbFiledText,
								"callback": function (data) {
									$scope.RadioSideList = data;
									$ionicLoading.hide();
									$BPSelectModal({
										title:title,
										bgAllColor:"positive-bg",
										selectValue:$scope.editData[field],
										text:"filedText",
										value:"filedValue",
										data:$scope.RadioSideList,
										onChange: function (item) {
										  $scope.editData[field] = item.value;
										  $scope.editData[field+'_txt'] = item.text;
										}
									  });
								},
								"finally": function () { 
									$ionicLoading.hide();
								}
						});
					}
		    },
			openCheckboxModal:function($scope,dataSource,defaultValue,title,field,dataItemCode,dbId,dbTable,dbFiledValue,dbFiledText)
			{
				$ionicLoading.show();
				if(dataSource=="dataItem")
				{
					$BPGetDataItem({
							"itemName": dataItemCode,
							"callback": function (data) {
								$scope.RadioSideList = data;
								$ionicLoading.hide();
								$BPCheckboxModal({
									title:title,
									bgAllColor:"positive-bg",
									selectValue:$scope.editData[field],
									text:"itemName",
									value:"itemValue",
									data:$scope.RadioSideList,
									onChange: function (value,text) {
									  if(value!=""){
										  $scope.editData[field] = value;
										  $scope.editData[field+'_txt'] = text;
									  }
									  else{
										  $scope.editData[field] = null;
										  $scope.editData[field+'_txt'] = null;
									  }
									}
								  });
							},
							"finally": function () { 
								$ionicLoading.hide();
							}
					});
				}
				else{
					$BPGetDataTable({
							"dbId": dbId,
							"dbTable": dbTable,
							"dbFiledValue": dbFiledValue,
							"dbFiledText": dbFiledText,
							"callback": function (data) {
								$scope.RadioSideList = data;
								$ionicLoading.hide();
								$BPCheckboxModal({
									title:title,
									bgAllColor:"positive-bg",
									selectValue:$scope.editData[field],
									text:"filedText",
									value:"filedValue",
									data:$scope.RadioSideList,
									onChange: function (item) {
									  $scope.editData[field] = item.value;
									  $scope.editData[field+'_txt'] = item.text;
									}
								  });
							},
							"finally": function () { 
								$ionicLoading.hide();
							}
					});
				}
			},
			openSearch:function($scope,$FormData,id,isFlow,r){
				  $scope.searchData = $FormData.getSearchList(id.toString());
				  //console.log($scope.searchData);
				  if($scope.searchModal != null)
				  {
					$scope.searchModal.remove();
				  }
				  
				  var searchHtml="<ion-side-menus>";
				  searchHtml+="<ion-side-menu-content>";
				  searchHtml+='<ion-header-bar class="bar-stable nav-bar-block nav-title-slide-ios7">';
				  searchHtml+='<button class="button button-clear " ng-click="closeSearchModal()"><i class="icon ion-ios-arrow-left"></i></button>';
				  searchHtml+='<button class="button button-clear"  menu-toggle="left"><i class="icon ion-navicon"></i></button>';
				  searchHtml+='	<div class="item-input-inset" style="width:100%;">';
				  searchHtml+='    <label class="item-input-wrapper">';
				  searchHtml+='    <i class="icon ion-ios-search placeholder-icon"></i>';
				  searchHtml+='    <input type="search" ng-model="searchData.keyword" placeholder="搜索">';
				  searchHtml+='    </label>';
				  searchHtml+='    </div>';
				  searchHtml+='    <button class="button button-clear" ng-click="doSearch()">';
				  searchHtml+='    <i class=" icon ion-ios-search"></i>';
				  searchHtml+='    </button>';
				  searchHtml+='    </ion-header-bar>';
				  searchHtml+='    <ion-content>';
				  searchHtml+='<div class="lr-searchTitle" ng-hide="searchData.records == 0 "><span>搜索结果 {{searchData.records}} 条</span></div>';
				  searchHtml+='<div class="list  list-inset lr-list-type2" style="margin-top:0px;">';
				  searchHtml+='<ion-list>';
				  
				  searchHtml+='<ion-item ng-repeat="item in searchData.items" class="item-remove-animate mt10" ng-click="openDetailsModal(item.CustmerFormId)">';
				  searchHtml+='<div class="need_list">';
				  var f=0;
				  for(var s=0;s<r.length;s++){

					  if(!r[s].hidden)
					  {
						  searchHtml+='<h2><span>['+r[s].label+']</span>{{item.'+r[s].name+'}}</h2>';
						  f=s;
						  break;
					  }
				  }
				  searchHtml+='<ul class="need_ul">';
				  for(var s=0;s<r.length;s++){

					  if(!r[s].hidden&&f!=s)
					  {
						  searchHtml+='<li><span>'+r[s].label+'：</span><em>{{item.'+r[s].name+'}}</em></li>';
					  }
				  }
				  searchHtml+='</ul>';
				  searchHtml+='</div>';
				  if(isFlow!=1)
					searchHtml+='<ion-option-button ng-click="doDelete(item)"><span class="lr-trash-circled"><i class="icon ion-ios-trash-outline"></i></span></ion-option-button>';
				  
				  searchHtml+='</ion-item>';

				  searchHtml+='</ion-list>';
				  searchHtml+='</div>';
				  searchHtml+='<ion-infinite-scroll ng-if="searchData.moredata" on-infinite="loadMoreSearch()" distance="1%"></ion-infinite-scroll>';
				  searchHtml+='</ion-content>';
				  searchHtml+='</ion-side-menu-content>';
				  
				  
				  //加入右边菜单
				  
				  searchHtml+='<!-- 左边栏 -->';
				  searchHtml+='<ion-side-menu side="left">';
                  searchHtml+='<ion-header-bar class="bar-stable nav-bar-block nav-title-slide-ios7">';
                  searchHtml+='<h1 class="title">条件检索</h1>';
                  searchHtml+='</ion-header-bar>';
				  searchHtml+='<ion-content class="has-header">';
				  
                  searchHtml+='<ion-list>';
				  //searchHtml+='<div class="item item-divider">选择 : {{searchData.searchtype}}</div>';
				  searchHtml+='<ion-radio nav-clear menu-close ng-model="searchData.searchtype" name="server-side" ng-value="\'All\'">全部</ion-radio>';
                  for(var s=0;s<r.length;s++){
					  if(!r[s].hidden)
						searchHtml+='<ion-radio nav-clear menu-close ng-model="searchData.searchtype" name="server-side" ng-value="\''+r[s].name+'\'">'+r[s].label+'</ion-radio>';
				  }
                  searchHtml+='</ion-list>';
				  searchHtml+='</ion-content>';
				  searchHtml+='</ion-side-menu>';
				  
				  
				  
				  
				  searchHtml+='</ion-side-menus>';
				  
				  var searchmodal=$ionicModal.fromTemplate(searchHtml, {
					 scope: $scope,
					 animation: 'slide-in-up',
				  });
				  $scope.searchModal = searchmodal;
				  $scope.searchModal.show();
			},
			removeItem($scope,Item){
				var ItemID=Item.CustmerFormId;
				$ionicLoading.show();
				$BPHttp.post({
					  "url": ApiUrl.removeInstanceFormApi,
					  "data": { "keyValue":ItemID},
					  "success": function (data) {
							$ionicLoading.hide();
							$BPTopAlert.show({ text: "数据删除成功！" });
							$scope.doRefresh();
					  },
					  "error": function () {
						$BPTopAlert.show({ text: "数据提交错误" });
					  },
					  "finally": function () { 
							$ionicLoading.hide();
					  }
				 });
			},
			dosubmit($scope,ItemID){
				  var item=$scope.FrmContent;
				  var field_list= $scope.form_field;
				  var self_field_list= $scope.self_form_field;
				  var field_array=[];
				  
				  for (var j = 0; j < item.length; j++) {
					for(var count=0;count<item[j].fields.length;count++)
					{
						field_array.push(item[j].fields[count]);
					}
				  }
				  //console.log($scope.editData);
				  var Validateflag=true;
				  for(var j=0;j<field_array.length; j++)
				  {
					  var field_id=field_array[j].field;
					  
					  
					  if(field_array[j].fieldType=="datetime")
					  {
						  if(field_array[j].dateformat == "date")
						  {
							$scope.editData[field_id]=$BPFormatDate($scope.editData[field_id], "yyyy-MM-dd");
						  }
						  else
						  {
							$scope.editData[field_id]=$BPFormatDate($scope.editData[field_id], "yyyy-MM-dd hh:mm");
						  }
					  }
					  else if(field_array[j].fieldType=='multiupload'||field_array[j].fieldType=='image'||field_array[j].fieldType=='upload')
					  {
						  var file_list="";
						  if($scope.editData[field_id]!=undefined){
							  //console.log($scope.editData[field_id]);
							  for(var item in $scope.editData[field_id])
							  {
								  var f_item=$scope.editData[field_id][item];
								  if(file_list!="")file_list+=",";
								  file_list+=f_item.fileId;
							  }
							  $scope.editData[field_id+"_listxx_Content"]=file_list;
							  //$scope.editData[field_id+"_txt"]=file_list;
						  }
					  }
					  field_array[j].value=$scope.editData[field_id];
					  if($scope.editData[field_id+"_listxx_Content"]!=""&&$scope.editData[field_id+"_listxx_Content"]!=undefined){
						  field_array[j].realValue=$scope.editData[field_id+"_listxx_Content"];
						  field_array[j].value=$scope.editData[field_id+"_listxx_Content"]; 
					  }
					  else if($scope.editData[field_id+"_txt"]!=""&&$scope.editData[field_id+"_txt"]!=undefined){
						field_array[j].realValue=$scope.editData[field_id+"_txt"];
					  }
					  else
						 field_array[j].realValue=$scope.editData[field_id];  
					  if(field_array[j].verify!="")
					  {
						  var ops={};
						  
						  ops.value=field_array[j].value;
						  ops.checkexpession=field_array[j].verify;
						  ops.errormsg=field_array[j].label;
						  
						  Validateflag=$BPValidform(ops);
						  if(Validateflag==false)
							  break;
					  }
				  }
				  
				  if(Validateflag!=false)
				  {
					 
					 if($scope.BillCode.length>0){
						 $ionicLoading.show();
						 //console.log($scope.frmEntity);
						 var frmid="";
						 if($scope.frmEntity.FrmId)
							 frmid=$scope.frmEntity.FrmId;
						 else
							 frmid=$scope.frmEntity.frmId;
						 $BPHttp.post({
							  "url": ApiUrl.getBillCodeApi,
							  "data": { "formid": frmid},
							  "success": function (data) {
									$ionicLoading.hide();
									if(data.status.code=="0"){
										
										for(var i in $scope.BillCode)	
										{
											
											$scope.editData[$scope.BillCode[i]]=data.status.desc;
											$scope.editData[$scope.BillCode[i]+"_txt"]=data.status.desc;
										}
										sendDataInit($scope,item,field_list,self_field_list,field_array,Validateflag,ItemID);
									}									
							  },
							  "error": function () {
								$BPTopAlert.show({ text: "数据获取错误" });
							  },
							  "finally": function () { 
									$ionicLoading.hide();
							  }
						 });
					 }
					 else{
						 sendDataInit($scope,item,field_list,self_field_list,field_array,Validateflag,ItemID);
					 }
				  }
				  
				  
				  
			}
		}
  }])
  //post 请求
  .factory('$BPSendData', ['$BPHttp','$ionicLoading','ApiUrl','$BPTopAlert','$ionicModal',function($BPHttp,$ionicLoading,ApiUrl,$BPTopAlert,$ionicModal){
	  return {
		init_data:function($scope,needshow,frmJson,itemid,html)
		{
				 $ionicLoading.show();
				 $BPHttp.post({
					  "url": ApiUrl.getInstanceEntityJsonApi,
					  "data": { "keyValue": itemid,"formRelationId": ""},
					  "success": function (data) {
						    $ionicLoading.hide();
							if(needshow){
								var modal=$ionicModal.fromTemplate(html, {scope: $scope,animation: 'slide-in-up',});
								$scope.editModal = modal;
								$scope.editModal.show();
							}
							//数据初始化
							var bind_Data=data.result;
							var selftdata=JSON.parse(bind_Data.dataInfo.frmInstanceJson);
							var fileList=JSON.parse(bind_Data.fileList);
							//console.log(selftdata);
							for(var i in selftdata)
							{
								var obj=selftdata[i];
								
								if(frmJson.type == 0)
								{
										var i=$scope.form_field.indexOf(obj.field);
									    if(obj.type=='messageInfo'){
											$scope.editData[$scope.self_form_field[i]]=obj.value;
											$scope.editData[$scope.self_form_field[i]+"_txt"]=obj.realValue;
											
											var messageList=[];
											if(obj.value!=undefined)
											{
												if(obj.value!="")
												{
													
													var records=JSON.parse(obj.value);
													if(records)
													{
														for(var sk in records){
															records[sk].files=[];
															if(records[sk].file_list!="")
															{
																//console.log(records[i].file_list);
																var list=records[sk].file_list.split(',');
																for(var f in list)
																{
																	for(var fileItem in fileList)
																	{
																		if(fileList[fileItem].fileId==list[f])
																		{
																			records[sk].files.push(fileList[fileItem]);
																		}
																	}
																}
															}
															messageList.push(records[sk]);
														}
													}
												}
											}
											$scope.editData[$scope.self_form_field[i]+"_list"]=messageList;
											//console.log(messageList);
											
										}
										else if(obj.type=='multiupload'||obj.type=='image'||obj.type=='upload'){
										
										if(obj.value!=undefined&&obj.value!=null&&obj.value!=""){
											var list=obj.value.split(',');
											$scope.editData[$scope.self_form_field[i]]=[];
											$scope.editData[$scope.self_form_field[i]+"_txt"]=[];
											for(var f in list)
											{
												for(var fileItem in fileList)
												{
													if(fileList[fileItem].fileId==list[f])
													{
														if($scope.editData[$scope.self_form_field[i]]==null)
														{
															  $scope.editData[$scope.self_form_field[i]]=[];
														}
														if($scope.editData[$scope.self_form_field[i]+"_txt"]==null)
														{
															  $scope.editData[$scope.self_form_field[i]+"_txt"]=[];
														}
														$scope.editData[$scope.self_form_field[i]].push(fileList[fileItem]);
														$scope.editData[$scope.self_form_field[i]+"_txt"].push(fileList[fileItem]);
													}
												}
											}
										}
									}
									else{
										if(needshow){
											if(obj.value!=""&&obj.value!=undefined){
												$scope.editData[$scope.self_form_field[i]]=obj.value;
												$scope.editData[$scope.self_form_field[i]+"_txt"]=obj.realValue;
											}
										}
										else{
											if(obj.type=='datetime')
											{
												$scope.editData[$scope.self_form_field[i]]=(obj.value==null||obj.value=="")?$scope.editData[$scope.self_form_field[i]]:obj.value;
												$scope.editData[$scope.self_form_field[i]+"_txt"]=(obj.value==null||obj.value=="")?$scope.editData[$scope.self_form_field[i]]:obj.value;
											}
											else{
												$scope.editData[$scope.self_form_field[i]]=($scope.editData[$scope.self_form_field[i]]==null||$scope.editData[$scope.self_form_field[i]]=="")?obj.value:$scope.editData[$scope.self_form_field[i]];
												$scope.editData[$scope.self_form_field[i]+"_txt"]=($scope.editData[$scope.self_form_field[i]+"_txt"]==null||$scope.editData[$scope.self_form_field[i]+"_txt"]=="")?obj.realValue:$scope.editData[$scope.self_form_field[i]+"_txt"];
											}
										}
									}
								}
								else{
										if(obj.type=='messageInfo'){
											$scope.editData[obj.field]=obj.value;
											$scope.editData[obj.field+"_txt"]=obj.realValue;
											var messageList=[];
											if(obj.value!=undefined)
											{
												if(obj.value!="")
												{
													var records=JSON.parse(obj.value);
													if(records)
													{
														for(var i in records){
															records[i].files=[];
															if(records[i].file_list!="")
															{
																//console.log(records[i].file_list);
																var list=records[i].file_list.split(',');
																for(var f in list)
																{
																	for(var fileItem in fileList)
																	{
																		if(fileList[fileItem].fileId==list[f])
																		{
																			records[i].files.push(fileList[fileItem]);
																		}
																	}
																}
															}
															messageList.push(records[i]);
														}
													}
												}
											}
											$scope.editData[obj.field+"_list"]=messageList;
											
										}
										else if(obj.type=='multiupload'||obj.type=='image'||obj.type=='upload'){
										if(obj.value!=null){
											var list=obj.value.split(',');
											$scope.editData[obj.field]=[];
											$scope.editData[obj.field+"_txt"]=[];
											for(var f in list)
											{
												for(var fileItem in fileList)
												{
													if(fileList[fileItem].fileId==list[f])
													{
														if($scope.editData[obj.field]==null)
														{
															  $scope.editData[obj.field]=[];
														}
														if($scope.editData[obj.field+"_txt"]==null)
														{
															  $scope.editData[obj.field+"_txt"]=[];
														}
														$scope.editData[obj.field].push(fileList[fileItem]);
														$scope.editData[obj.field+"_txt"].push(fileList[fileItem]);
													}
												}
											}
										}
									}
									else if(obj.value!=""&&obj.value!=undefined){
										if(needshow){
											$scope.editData[obj.field]=obj.value;
											$scope.editData[obj.field+"_txt"]=obj.realValue;
										}
										else
										{
											if(obj.type=='datetime')
											{
												$scope.editData[obj.field]=(obj.value==null||obj.value=="")?$scope.editData[obj.field]:obj.value;
												$scope.editData[obj.field+"_txt"]=(obj.value==null||obj.value=="")?$scope.editData[obj.field]:obj.value;
											}
											else{
												$scope.editData[obj.field]=($scope.editData[obj.field]==null||$scope.editData[obj.field]=="")?obj.value:$scope.editData[obj.field];
												$scope.editData[obj.field+"_txt"]=($scope.editData[obj.field+"_txt"]==null||$scope.editData[obj.field+"_txt"]=="")?obj.realValue:$scope.editData[obj.field+"_txt"];
											}
										}
									}
								}
							}
							
							
					  },
					  "error": function () {
						$BPTopAlert.show({ text: "数据获取错误" });
					  },
					  "finally": function () { 
							$ionicLoading.hide();
					  }
				 });
		},
		send_data:function($scope,ItemID,field_array) {
			$ionicLoading.show();
			var data=[];
			for(var i in field_array)
			{
				if(field_array[i].value==undefined) field_array[i].value="";
				if(field_array[i].realValue==undefined) field_array[i].realValue="";
				
				if(field_array[i].fieldType=="text")
				{
					if(field_array[i].selfield)
						data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue,control_rule:field_array[i].control_rule,control_uniq:field_array[i].control_uniq});
					else
						data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue,control_rule:field_array[i].control_rule,control_uniq:field_array[i].control_uniq});
				}
				else if(field_array[i].fieldType=="messageInfo"||field_array[i].fieldType=="currentInfo"||field_array[i].fieldType=="multiUserInfo")
				{
					if(field_array[i].selfield)
						data.push({infoType:field_array[i].infoType,type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue});
					else
						data.push({infoType:field_array[i].infoType,type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue});
				}
				else{
					if(field_array[i].selfield)
						data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue});
					else
						data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue});
				}
				
				
				/*
				if(field_array[i].selfield){
					data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].selfield,realValue:field_array[i].realValue});
				}
				else{
					data.push({type:field_array[i].fieldType,value:field_array[i].value,field:field_array[i].field,realValue:field_array[i].realValue});
				}*/
			}
			//console.log($scope.frmEntity);
			var frmID=$scope.frmEntity.id;
			
			var postData = {
                FrmContentId: frmID,
                FrmInstanceJson: JSON.stringify(data),
                ObjectId: $scope.id
            };
			//console.log(postData);
			//console.log(ItemID);
			
			$BPHttp.post({
				  "url": ApiUrl.saveInstanceEntityJsonApi,
				  "data": { "keyValue":ItemID,"postData": postData},
				  "success": function (data) {
						$ionicLoading.hide();
						if(data.status.code=="0"){
							$BPTopAlert.show({ text: "数据提交成功！" });
							$scope.editModal.remove();
							$scope.doRefresh();
						}
						else{
							$BPTopAlert.show({ text: "数据提交错误！" });
						}
				  },
				  "error": function () {
					$BPTopAlert.show({ text: "数据提交错误" });
				  },
				  "finally": function () { 
						$ionicLoading.hide();
				  }
			 });
		}
	  }
  }])
  //post 请求
  .factory('$BPHttp', [
    '$rootScope',
    '$base64',
    '$http',
    '$BPTopAlert',
    'UserInfo',
	'$state',
  function ($rootScope, $base64, $http, $BPTopAlert, UserInfo,$state) {
      return {
          post: httpPost
      };
      function httpPost(opts) {
          var scope = $rootScope.$new(true);
          ionic.extend(scope, {
              data: {},
              error: function () { }
          }, opts || {});
          var userInfo = UserInfo.get();
          var platform = ionic.Platform.platform();
          $http.post(scope.url,
             $base64.encode(JSON.stringify({
                 "data": scope.data,
                 token: userInfo.token,
                 userid: userInfo.userid,
                 platform: platform,
             })
         ))
         .success(function (data) {
              if (scope.isverify) {
                  if (data.status.code != "0") {
					  if(data.status.desc=="后台无登录信息")
					  {
						  $BPTopAlert.show({ text: data.status.desc });
						  UserInfo.clear();
						  $state.go("login");
					  }
					  else{
						  $BPTopAlert.show({ text: data.status.desc });
						  return false;
					  }
                  }
              }
              scope.success(data);
          })
          .error(function () { scope.error(); })
          .finally(function () { scope.finally(); });
      }
  }])
   //本地存储数据
  .factory('$BPLocals', ['$window', function ($window) {
      return {
          //存储单个属性
          set: function (key, value) {
              $window.localStorage[key] = value;
          },
          //读取单个属性
          get: function (key, defaultValue) {
              return $window.localStorage[key] || defaultValue;
          },
          //存储对象，以JSON格式存储
          setObject: function (key, value) {
              $window.localStorage[key] = JSON.stringify(value);
          },
          //读取对象
          getObject: function (key) {
              return JSON.parse($window.localStorage[key] || '{}');
          }
      }
  }])
  //弹层
  .factory('$BPPopup', ['$rootScope', '$ionicPopup', function ($rootScope, $ionicPopup) {
      return {
          confirm: confirm
      }
      function confirm(opts) {
          var scope = $rootScope.$new(true);
          ionic.extend(scope, {
              title: '<p> </p>是否确定?<p> </p>',
              cancelText: '取消',
              okText: '确定',
              okType: 'positive',
              ok: function () { },
              cancel: function () { },
          }, opts || {});

          var confirmPopup = $ionicPopup.confirm(scope);
          confirmPopup.then(function (res) {
              if (res) {
                  scope.ok();
              }
              else {
                  scope.cancel();
              }
          });
      };
  }])
  //触发下拉刷新
  .service('$BPTriggerRefresh', ['$timeout', '$ionicScrollDelegate', function ($timeout, $ionicScrollDelegate) {
      /**
       * Trigger the pull-to-refresh on a specific scroll view delegate handle.
       * @param {string} delegateHandle - The `delegate-handle` assigned to the `ion-content` in the view.
       */
      this.triggerRefresh = function (delegateHandle) {

          $timeout(function () {

              var scrollView = $ionicScrollDelegate.$getByHandle(delegateHandle).getScrollView();

              if (!scrollView) return;

              scrollView.__publish(
                scrollView.__scrollLeft, -scrollView.__refreshHeight,
                scrollView.__zoomLevel, true);

              var d = new Date();

              scrollView.refreshStartTime = d.getTime();

              scrollView.__refreshActive = true;
              scrollView.__refreshHidden = false;
              if (scrollView.__refreshShow) {
                  scrollView.__refreshShow();
              }
              if (scrollView.__refreshActivate) {
                  scrollView.__refreshActivate();
              }
              if (scrollView.__refreshStart) {
                  scrollView.__refreshStart();
              }

          });

      }
  }])
  //格式化时间
  .factory('$BPFormatDate', function () {
      return formatDate = function (v, format) {
          if (!v) return "";
          var d = v;
          if (typeof v === 'string') {
              if (v.indexOf("/Date(") > -1)
                  d = new Date(parseInt(v.replace("/Date(", "").replace(")/", ""), 10));
              else
                  d = new Date(Date.parse(v.replace(/-/g, "/").replace("T", " ").split(".")[0]));//.split(".")[0] 用来处理出现毫秒的情况，截取掉.xxx，否则会出错
          }
          var o = {
              "M+": d.getMonth() + 1,  //month
              "d+": d.getDate(),       //day
              "h+": d.getHours(),      //hour
              "m+": d.getMinutes(),    //minute
              "s+": d.getSeconds(),    //second
              "q+": Math.floor((d.getMonth() + 3) / 3),  //quarter
              "S": d.getMilliseconds() //millisecond
          };
          if (/(y+)/.test(format)) {
              format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
          }
          for (var k in o) {
              if (new RegExp("(" + k + ")").test(format)) {
                  format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
              }
          }
          return format;

      }
  })
  .factory('$BPFormPageModal',['$BPFormMethod','$BPDataIsAll','$BPPopup','$BPSelectModal','$BPHttp','ApiUrl','$ionicModal','$BPFormatDate','$BaseInfo',function($BPFormMethod,$BPDataIsAll,$BPPopup,$BPSelectModal,$BPHttp,ApiUrl,$ionicModal,$BPFormatDate,$BaseInfo){
	
		return function ($scope,needSave,callbackRemmove) {
			$scope.flowLevelSideList = [
			  { text: "重要", value: "1", bgColor:"bgcolor_a" },
			  { text: "普通", value: "2", bgColor:"bgcolor_b" },
			  { text: "一般", value: "3", bgColor:"bgcolor_c" }
			];
			$scope.openFlowLevelModal = function () {
				$BPSelectModal({
					title:"重要等级",
					bgAllColor:"positive-bg",
					selectValue:$scope.editData.wflevel,
					text:"text",
					value:"value",
					data:$scope.flowLevelSideList,
					onChange: function (item) {
					  $scope.editData.wflevel = item.value;
					  $scope.editData.wfleveltext = item.text;
					}
				});
			};
			
			//轨迹
			$scope.openFlowRptModal=function(itemid){
				  
				  
				  $BPHttp.post({
					  "url": ApiUrl.getflowProcessListApi,
					  "data": { "flowid": itemid},
					  "isverify": true,
					  "success": function (data) {
						  
						  var flow = data.result;
						  if(flow.activityId){
							  
							  var Rptlist=[];
							  var tagname = { "-1": "终止", "1": "下发", "0": "驳回","999": "正在处理" };
							  for(var i in $scope.SchemeContentObj.Flow.nodes)
							  {
								  if($scope.SchemeContentObj.Flow.nodes[i].type=="startround")
								  {
									   Rptlist.push({Taged:"发起",NodeName:$scope.SchemeContentObj.Flow.nodes[i].name,TagedTime:$BPFormatDate(flow.createDate, 'yyyy-MM-dd hh:mm'),UserName:flow.createUserName});
								  }
								  else if($scope.SchemeContentObj.Flow.nodes[i].setInfo!= undefined && $scope.SchemeContentObj.Flow.nodes[i].setInfo.Taged != undefined)
								  {
									  var item=$scope.SchemeContentObj.Flow.nodes[i];
									  Rptlist.push({Taged:tagname[item.setInfo.Taged],NodeName:item.name,TagedTime:$BPFormatDate(item.setInfo.TagedTime,'yyyy-MM-dd hh:mm'),UserName:$BaseInfo.getUserList()[item.setInfo.UserId].realName});
								  }
							  }
							  //console.log(Rptlist);
							  $scope.nodes=Rptlist;
							  $ionicModal.fromTemplateUrl('templates/homeApps/form/Rpt.html', {
								scope: $scope,
								animation: 'lr-slide-in-right',
								focusFirstInput: true
							  }).then(function (modal) {
								$scope.rptModal = modal;
								$scope.rptModal.show();
							  });
							  
						  }
						  else{
							  $BPTopAlert.show({ text: "流程轨迹获取失败" });
						  }
					  },
					  "error": function () {
						  $BPTopAlert.show({ text: "流程信息获取失败" });
					  },
					  "finally": function () {
						  $ionicLoading.hide();
					  }
				  });
				  
				  
				  
			};
			
			$scope.closeRptModel=function(){
				  $scope.rptModal.remove();
			};
			
			$scope.flowTypeSideList = [
			  { text: "直接发送", value: "0", bgColor:"bgcolor_a" },
			  { text: "草稿保存", value: "3", bgColor:"bgcolor_b" }
			];
			
			$scope.openFlowSaveModal = function () {
				$BPSelectModal({
					title:"发送类型",
					bgAllColor:"positive-bg",
					selectValue:$scope.editData.type,
					text:"text",
					value:"value",
					data:$scope.flowTypeSideList,
					onChange: function (item) {
					  $scope.editData.type = item.value;
					  $scope.editData.typetext = item.text;
					}
				});
			};
			$scope.openAreaSelectModal=function(dataType,field){$BPFormMethod.openAreaSelectModal($scope,dataType,field);};
			//文件下载
			$scope.getFileContents=function(file){$BPFormMethod.getFileContents($scope,file);};
			//图片预览
			$scope.showImageModal = function(url) {$BPFormMethod.showImageModal($scope,url);}
			//角色选择、部门选择、岗位选择、用户选择
			$scope.openBaseSelectModal=function(dataType,field){$BPFormMethod.openBaseSelectModal($scope,dataType,field);};
			//删除文件
			$scope.doDeleteFile=function(file,field){$BPFormMethod.doDeleteFile($scope,file,field);};
			//文件选择
			$scope.openFileSelectModal=function(type,field){$BPFormMethod.openFileSelectModal($scope,type,field);};
			//多选项目
			$scope.openCheckboxModal=function (dataSource,defaultValue,title,field,dataItemCode,dbId,dbTable,dbFiledValue,dbFiledText) {$BPFormMethod.openCheckboxModal($scope,dataSource,defaultValue,title,field,dataItemCode,dbId,dbTable,dbFiledValue,dbFiledText);};
			//单选项目
			$scope.openRadioModal= function (dataSource,defaultValue,title,field,dataItemCode,dbId,dbTable,dbFiledValue,dbFiledText) {$BPFormMethod.openRadioModal($scope,dataSource,defaultValue,title,field,dataItemCode,dbId,dbTable,dbFiledValue,dbFiledText);};
			//客户选择
			$scope.openCrmModal=function (title,field){$BPFormMethod.openCrmSelectModal($scope,title,field);};
			
			//信息记录 记录编辑
			$scope.openMessageSelectModal=function(fieldType,field,infoType,listitem,lablename){$BPFormMethod.openMessageSelectModal($scope,fieldType,field,infoType,listitem,lablename);};
			//信息记录 整体记录删除
			$scope.doDeleteMessage=function(listitem,field){$BPFormMethod.doDeleteMessage($scope,listitem,field);};
			//信息记录 文件记录删除
			$scope.doDeleteFileMessage=function(file,listitem,field){$BPFormMethod.doDeleteFileMessage($scope,file,listitem,field);};
			
			
			return function () {
              if (callbackRemmove != undefined) {
                  callbackRemmove();
              }
			 
			  if(needSave){
				  if($BPDataIsAll.isHave($scope.editData)) {
					$BPPopup.confirm({
					  title: '<p> </p>你输入的内容未保存，是否放弃本次编辑?<p> </p>',
					  okText: '放弃',
					  ok: function () {
						  if ($scope.editModal != undefined) 
							$scope.editModal.remove();
						  else{
							  $scope.closeEditModal();
						  }
					  }
					});
				  }else {
					 if ($scope.editModal != undefined) 
							$scope.editModal.remove();
					 else{
							  $scope.closeEditModal();
					}
				  }
			  }
			  else{
				  if ($scope.editModal != undefined) 
						$scope.editModal.remove();
				  else{
					 $scope.closeEditModal();
				  }
			  }
          };
		};
	}
  ])
  //页面模型
  .factory('$BPPageModal', ['$ionicModal', function ($ionicModal) {

      return function (scope, templateUrl, fnMethod, callbackRemmove) {
          var pageModel;
          scope.openPageModel = function (pageId, id) {
              var _pageId = templateUrl + pageId;
              if (pageModel != null) {
                  pageModel.remove();
              }
              if (fnMethod != undefined) {
                  fnMethod(id);
              }
              $ionicModal.fromTemplateUrl(templateUrl + pageId, {
                  scope: scope,
                  animation: 'lr-slide-in-right'
              }).then(function (modal) {
                  pageModel = modal;
                  pageModel.show();
              });
          };
          return function () {
              if (callbackRemmove != undefined) {
                  callbackRemmove();
              }
              pageModel.remove();
          };
      };
  }])
  //选择页面模型
  .factory('$BPCheckboxModal', ['$rootScope', '$ionicModal', function ($rootScope, $ionicModal) {
      var selcetModal = null;
      var scope = $rootScope.$new(true);
      var onChange = null;
	  scope.selectData = [];
      scope.selectValue = "";
	  scope.selectText = "";
      scope.closeSelectModal = function () {
          selcetModal.remove();
      };
      scope.doSubmit = function () {
		  var item=scope.selectData;
		  var return_value="";
		  var return_txt="";
		  for(var i in item)
		  {
			  
			  if(item[i].selected){
				  if(return_value!=""&&return_txt!="")
				  {
					  return_txt+=",";
					  return_value+=",";
				  }
				  return_value+=item[i].value;
				  return_txt+=item[i].text;
			  }
		  }
		  
		  if (onChange != null) {
              onChange(return_value,return_txt);
          }
          selcetModal.remove();
      };
      return function (ops) {
          if (selcetModal != null) {
              selcetModal.remove();
          };
          scope.selectValue = ops.selectValue;
          scope.selectData = [];
          for (var i in ops.data) {
			  if(ops.selectValue==null) ops.selectValue="";
			  var tar_array=ops.selectValue.split(',');
			  if(tar_array.indexOf(ops.data[i][ops.value])>=0)
				scope.selectData.push({ text: ops.data[i][ops.text], value: ops.data[i][ops.value], bgColor: ops.data[i][ops.bgColor],selected:true });
			  else
			    scope.selectData.push({ text: ops.data[i][ops.text], value: ops.data[i][ops.value], bgColor: ops.data[i][ops.bgColor],selected:false });
          }
          scope.title = ops.title;
          scope.bgAllColor = ops.bgAllColor;
          onChange = ops.onChange;
          $ionicModal.fromTemplateUrl('templates/util/util-checkboxModal.html', {
              scope: scope,
              animation: 'slide-in-up'
          }).then(function (modal) {
              selcetModal = modal;
              selcetModal.show();
          });
      };

  }])
  //数据验证
  .factory('$BPValidform',['$BPTopAlert',function ($BPTopAlert) {
	 function isNotNull(obj) {
		var obj = $.trim(obj);
        if (obj.length == 0 || obj == null || obj == undefined) {
            return true;
        }
        else
            return false;
      }
	  //验证数字 num
      function isInteger(obj) {
        reg = /^[-+]?\d+$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
      }
	  function isIntegerOrNull(obj) {
        var controlObj = $.trim(obj);
        if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
            return true;
        }
        reg = /^[-+]?\d+$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
      }
	  function isEmail(obj) {
		reg = /^\w{3,}@\w+(\.\w+)+$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
	  }
	  function isEmailOrNull(obj) {
        var controlObj = $.trim(obj);
        if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
            return true;
        }
        reg = /^\w{3,}@\w+(\.\w+)+$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
      }
	  function isEnglishStr(obj) {
        reg = /^[a-z,A-Z]+$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
      };
	  function isEnglishStrOrNull(obj) {
        var controlObj = $.trim(obj);
        if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
            return true;
        }
        reg = /^[a-z,A-Z]+$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
      }
	  function isLenNum(obj) {
        reg = /^[0-9]+$/;
        obj = $.trim(obj);
        if (obj.length > n)
            return false;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
      }
	  function isLenNumOrNull(obj) {
        var controlObj = $.trim(obj);
        if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
            return true;
        }
        reg = /^[0-9]+$/;
        obj = $.trim(obj);
        if (obj.length > n)
            return false;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
      }
	  this.isLenStr=function (obj) {
        obj = $.trim(obj);
        if (obj.length == 0 || obj.length > n)
            return false;
        else
            return true;
      };
	  function isLenStrOrNull(obj) {
        var controlObj = $.trim(obj);
        if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
            return true;
        }
        obj = $.trim(obj);
        if (obj.length > n)
            return false;
        else
            return true;
      }
	  function isTelephone(obj) {
        reg = /^(\d{3,4}\-)?[1-9]\d{6,7}$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
      }
	  function isTelephoneOrNull(obj) {
        var controlObj = $.trim(obj);
        if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
            return true;
        }
        reg = /^(\d{3,4}\-)?[1-9]\d{6,7}$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
      }
	  function isMobile(obj) {
		reg = /^(\+\d{2,3}\-)?\d{11}$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
	  }
	  function isMobileOrnull(obj) {
		var controlObj = $.trim(obj);
        if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
            return true;
        }
        reg = /^(\+\d{2,3}\-)?\d{11}$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
	  };
	  function isMobileOrPhone(obj) {
		reg_mobile = /^(\+\d{2,3}\-)?\d{11}$/;
        reg_phone = /^(\d{3,4}\-)?[1-9]\d{6,7}$/;
        if (!reg_mobile.test(obj) && !reg_phone.test(obj)) {
            return false;
        } else {
            return true;
        }
	  }
	  function isMobileOrPhoneOrNull(obj) {
		var controlObj = $.trim(obj);
        if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
            return true;
        }
        reg = /^(\+\d{2,3}\-)?\d{11}$/;
        reg2 = /^(\d{3,4}\-)?[1-9]\d{6,7}$/;
        if (!reg.test(obj) && !reg2.test(obj)) {
            return false;
        } else {
            return true;
        }
	  }
	  function isUri(obj) {
		reg = /^http:\/\/[a-zA-Z0-9]+\.[a-zA-Z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
	  }
	  function isUriOrnull(obj) {
		var controlObj = $.trim(obj);
        if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
            return true;
        }
        reg = /^http:\/\/[a-zA-Z0-9]+\.[a-zA-Z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
        if (!reg.test(obj)) {
            return false;
        } else {
            return true;
        }
	  }
	  function isEqual(obj1, controlObj) {
		if (obj1.length != 0 && controlObj.length != 0) {
            if (obj1 == controlObj)
                return true;
            else
                return false;
        }
        else
            return false;
	  }
	  function isDate(obj) {
        if (obj.length != 0) {
            reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/;
            if (!reg.test(obj)) {
                return false;
            }
            else {
                return true;
            }
        }
	  }
	  //判断日期类型是否为YYYY-MM-DD格式的类型 date或者null,空
	  function isDateOrNull(obj) {
			var controlObj = $.trim(obj);
			if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
				return true;
			}
			if (obj.length != 0) {
				reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/;
				if (!reg.test(obj)) {
					return false;
				}
				else {
					return true;
				}
			}
		}
        //判断日期类型是否为YYYY-MM-DD hh:mm:ss格式的类型 datetime
        function isDateTime(obj) {
			if (obj.length != 0) {
				reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
				if (!reg.test(obj)) {
					return false;
				}
				else {
					return true;
				}
			}
        }
		//判断日期类型是否为YYYY-MM-DD hh:mm:ss格式的类型 datetime或者null,空
		function isDateTimeOrNull(obj) {
			var controlObj = $.trim(obj);
			if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
				return true;
			}
			if (obj.length != 0) {
				reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
				if (!reg.test(obj)) {
					return false;
				}
				else {
					return true;
				}
			}
		}
		//判断日期类型是否为hh:mm:ss格式的类型 time
		function isTime(obj) {
			if (obj.length != 0) {
				reg = /^((20|21|22|23|[0-1]\d)\:[0-5][0-9])(\:[0-5][0-9])?$/;
				if (!reg.test(obj)) {
					return false;
				}
				else {
					return true;
				}
			}
		}
		//判断日期类型是否为hh:mm:ss格式的类型 time或者null,空
		function isTimeOrNull(obj) {
			var controlObj = $.trim(obj);
			if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
				return true;
			}
			if (obj.length != 0) {
				reg = /^((20|21|22|23|[0-1]\d)\:[0-5][0-9])(\:[0-5][0-9])?$/;
				if (!reg.test(obj)) {
					return false;
				}
				else {
					return true;
				}
			}
		}
		//判断输入的字符是否为中文 cchar 
		function isChinese(obj) {
			if (obj.length != 0) {
				reg = /^[\u0391-\uFFE5]+$/;
				if (!reg.test(str)) {
					return false;
				}
				else {
					return true;
				}
			}
		}
		//判断输入的字符是否为中文 cchar或者null,空
		function isChineseOrNull(obj) {
			var controlObj = $.trim(obj);
			if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
				return true;
			}
			if (obj.length != 0) {
				reg = /^[\u0391-\uFFE5]+$/;
				if (!reg.test(str)) {
					return false;
				}
				else {
					return true;
				}
			}
		}
		//判断输入的邮编(只能为六位)是否正确 zip
		function isZip(obj) {
			if (obj.length != 0) {
				reg = /^\d{6}$/;
				if (!reg.test(str)) {
					return false;
				}
				else {
					return true;
				}
			}
		}
		//判断输入的邮编(只能为六位)是否正确 zip或者null,空
		function isZipOrNull(obj) {
			var controlObj = $.trim(obj);
			if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
				return true;
			}
			if (obj.length != 0) {
				reg = /^\d{6}$/;
				if (!reg.test(str)) {
					return false;
				}
				else {
					return true;
				}
			}
		}
		//判断输入的字符是否为双精度 double
		function isDouble(obj) {
			if (obj.length != 0) {
				reg = /^[-\+]?\d+(\.\d+)?$/;
				if (!reg.test(obj)) {
					return false;
				}
				else {
					return true;
				}
			}
		};
		//判断输入的字符是否为双精度 double或者null,空
		function isDoubleOrNull(obj) {
			var controlObj = $.trim(obj);
			if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
				return true;
			}
			if (obj.length != 0) {
				reg = /^[-\+]?\d+(\.\d+)?$/;
				if (!reg.test(obj)) {
					return false;
				}
				else {
					return true;
				}
			}
		}
		//判断是否为身份证 idcard
		function isIDCard(obj) {
			if (obj.length != 0) {
				reg = /^\d{15}(\d{2}[A-Za-z0-9;])?$/;
				if (!reg.test(obj))
					return false;
				else
					return true;
			}
		};
		//判断是否为身份证 idcard或者null,空
		function isIDCardOrNull(obj) {
			var controlObj = $.trim(obj);
			if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
				return true;
			}
			if (obj.length != 0) {
				reg = /^\d{15}(\d{2}[A-Za-z0-9;])?$/;
				if (!reg.test(obj))
					return false;
				else
					return true;
			}
		};
		//判断是否为IP地址格式
		function isIP(obj) {
			var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/g //匹配IP地址的正则表达式 
			if (re.test(obj)) {
				if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256) return true;
			}
			return false;
		};
		//判断是否为IP地址格式 或者null,空
		function isIPOrNull(obj) {
			var controlObj = $.trim(obj);
			if (controlObj.length == 0 || controlObj == null || controlObj == undefined) {
				return true;
			}
			var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/g //匹配IP地址的正则表达式 
			if (re.test(obj)) {
				if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256) return true;
			}
			return false;
		}
	  
	  
		function ValidationMessage(Validatemsg)
		{
			  $BPTopAlert.show({ text: Validatemsg });
		}
	  return function(ops){
		  var checkexpession = ops.checkexpession;
          var errormsg = ops.errormsg;
		  if (checkexpession != undefined) {
            if (errormsg == undefined) {
                errormsg = "";
            }
		  }
		  var Validateflag = true;
		  var value = ops.value;
		  switch (checkexpession) {
			case "NotNull":
				{
					if (isNotNull(value)) {
						Validatemsg = errormsg + "不能为空！\n";
						Validateflag = false;
						ValidationMessage(Validatemsg); 
						return false;
					}
					break;
				}
			 case "Num":
                    {
                        if (!isInteger(value)) {
                            Validatemsg = errormsg + "必须为数字！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); 
							return false;
                        }
                        break;
                    }
			 case "NumOrNull":
                    {
                        if (!isIntegerOrNull(value)) {
                            Validatemsg = errormsg + "必须为数字！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); 
							return false;
                        }
                        break;
                    }
                case "Email":
                    {
                        if (!isEmail(value)) {
                            Validatemsg = errormsg + "必须为E-mail格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); 
							return false;
                        }
                        break;
                    }
                case "EmailOrNull":
                    {
                        if (!isEmailOrNull(value)) {
                            Validatemsg = errormsg + "必须为E-mail格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); 
							return false;
                        }
                        break;
                    }
                case "EnglishStr":
                    {
                        if (!isEnglishStr(value)) {
                            Validatemsg = errormsg + "必须为字符串！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); 
							return false;
                        }
                        break;
                    }
                case "EnglishStrOrNull":
                    {
                        if (!isEnglishStrOrNull(value)) {
                            Validatemsg = errormsg + "必须为字符串！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); 
							return false;
                        }
                        break;
                    }
                case "LenNum":
                    {
                        if (!isLenNum(value, ops.length)) {
                            Validatemsg = errormsg + "必须为" + ops.length + "位数字！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); 
							return false;
                        }
                        break;
                    }
                case "LenNumOrNull":
                    {
                        if (!isLenNumOrNull(value, ops.length)) {
                            Validatemsg = errormsg + "必须为" + ops.length + "位数字！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); 
							return false;
                        }
                        break;
                    }
                case "LenStr":
                    {
                        if (!isLenStr(value, ops.length)) {
                            Validatemsg = errormsg + "必须小于" + ops.length + "位字符！\n";
                            Validateflag = false;
                            ValidationMessage(alidatemsg); return false;
                        }
                        break;
                    }
                case "LenStrOrNull":
                    {
                        if (!isLenStrOrNull(value, ops.length)) {
                            Validatemsg = errormsg + "必须小于" + $(this).attr("length") + "位字符！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "Phone":
                    {
                        if (!isTelephone(value)) {
                            Validatemsg = errormsg + "必须电话格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "PhoneOrNull":
                    {
                        if (!isTelephoneOrNull(value)) {
                            Validatemsg = errormsg + "必须电话格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "Fax":
                    {
                        if (!isTelephoneOrNull(value)) {
                            Validatemsg = errormsg + "必须为传真格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "Mobile":
                    {
                        if (!isMobile(value)) {
                            Validatemsg = errormsg + "必须为手机格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "MobileOrNull":
                    {
                        if (!isMobileOrnull(value)) {
                            Validatemsg = errormsg + "必须为手机格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "MobileOrPhone":
                    {
                        if (!isMobileOrPhone(value)) {
                            Validatemsg = errormsg + "必须为电话格式或手机格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "MobileOrPhoneOrNull":
                    {
                        if (!isMobileOrPhoneOrNull(value)) {
                            Validatemsg = errormsg + "必须为电话格式或手机格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "Uri":
                    {
                        if (!isUri(value)) {
                            Validatemsg = errormsg + "必须为网址格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "UriOrNull":
                    {
                        if (!isUriOrnull(value)) {
                            Validatemsg = errormsg + "必须为网址格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "Equal":
                    {
                        if (!isEqual(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "不相等！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "Date":
                    {
                        if (!isDate(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为日期格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "DateOrNull":
                    {
                        if (!isDateOrNull(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为日期格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "DateTime":
                    {
                        if (!isDateTime(value,ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为日期时间格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "DateTimeOrNull":
                    {
                        if (!isDateTimeOrNull(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为日期时间格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "Time":
                    {
                        if (!isTime(value,ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为时间格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "TimeOrNull":
                    {
                        if (!isTimeOrNull(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为时间格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "ChineseStr":
                    {
                        if (!isChinese(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为中文！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "ChineseStrOrNull":
                    {
                        if (!isChineseOrNull(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为中文！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "Zip":
                    {
                        if (!isZip(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为邮编格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "ZipOrNull":
                    {
                        if (!isZipOrNull(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为邮编格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "Double":
                    {
                        if (!isDouble(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为小数！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "DoubleOrNull":
                    {
                        if (!isDoubleOrNull(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为小数！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "IDCard":
                    {
                        if (!isIDCard(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为身份证格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "IDCardOrNull":
                    {
                        if (!isIDCardOrNull(value,ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为身份证格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "IsIP":
                    {
                        if (!isIP(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为IP格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                case "IPOrNull":
                    {
                        if (!isIPOrNullOrNull(value, ops.eqvalue)) {
                            Validatemsg = errormsg + "必须为IP格式！\n";
                            Validateflag = false;
                            ValidationMessage(Validatemsg); return false;
                        }
                        break;
                    }
                default:
                    break;
		  }
	  }  
  }])
  //选择页面模型
  .factory('$BPSelectModal', ['$rootScope', '$ionicModal', function ($rootScope, $ionicModal) {
      var selcetModal = null;
      var scope = $rootScope.$new(true);
      var onChange = null;
	  var onClick = null;
      scope.selectValue = "";
      scope.closeSelectModal = function () {
          selcetModal.remove();
      };
      scope.changeSelectModal = function (item) {
          if (onChange != null) {
              onChange(item);
          }
          selcetModal.remove();
      };
	  scope.clickSelectModal = function (item) {
          if (onClick != null) {
              onClick(item);
			  selcetModal.remove();
          }
      };
      return function (ops) {
          if (selcetModal != null) {
              selcetModal.remove();
          };
          scope.selectValue = ops.selectValue;
          scope.selectData = [];
          for (var i in ops.data) {
              scope.selectData.push({ text: ops.data[i][ops.text], value: ops.data[i][ops.value], bgColor: ops.data[i][ops.bgColor] });
          }
          scope.title = ops.title;
          scope.bgAllColor = ops.bgAllColor;
          onChange = ops.onChange;
		  onClick=ops.onClick;
          $ionicModal.fromTemplateUrl('templates/util/util-selectModal.html', {
              scope: scope,
              animation: 'slide-in-up'
          }).then(function (modal) {
              selcetModal = modal;
              selcetModal.show();
          });
      };

  }])
  .factory('$BPMessagePageModal', ['$rootScope', '$ionicModal','$filter','UserInfo','$cordovaActionSheet','$SelectPicture','$BPTopAlert',function ($rootScope, $ionicModal,$filter,UserInfo,$cordovaActionSheet,$SelectPicture,$BPTopAlert) {
	  var MessageModal = null;
	  
      var scope = $rootScope.$new(true);
      var onChange = null;
	  scope.messageData={};

      scope.closeMessageModal = function () {
          MessageModal.remove();
      };
	  scope.doMessageSubmit = function () {
          if (onChange != null) {
			  if(scope.messageData.files==null||scope.messageData.files==undefined)
				  $BPTopAlert.show({ text: "请添加文件再提交" });
			  else if(scope.messageData.files.length==0)
			  {
				  $BPTopAlert.show({ text: "请添加文件再提交" });
			  }
			  else{
				  onChange(scope.messageData);
				  MessageModal.remove();
			  }
          }
      };
	  //信息记录 文件选择(窗口模式)
	  scope.openFileSelectModalForMessage=function(field){
		    //$BPFormMethod.openFileSelectModalForMessage(scope,field);
		    var options = {
				title: '请选择',
				buttonLabels: ['相机', '图库'],
				addCancelButtonWithLabel: '取消',
				androidEnableCancelButton: true,
				winphoneEnableCancelButton: true
			};
			document.addEventListener("deviceready", function() {
				$cordovaActionSheet.show(options)
					.then(function(btnIndex) {
						var index = btnIndex;
						
						switch (index){  
						   case 1:
							 $SelectPicture.chooseSinglePicture({
								 "width":100,
								 "height":100,
								 "success":function (data) {
									  if(scope.messageData.files==null)
									  {
										  scope.messageData.files=[];
									  }
									  scope.messageData.files.push(data);
									  //console.log($scope.editData[field]);
								  }
							 });	
							 break;  
						   case 2:
							 $SelectPicture.choosePictures({
								 "success": function (data) {
									  if(scope.messageData.files==null)
									  {
										  scope.messageData.files=[];
									  }
									  scope.messageData.files.push(data);
									  //console.log($scope.editData[field]);
								  }
							 });						   
							 break;  
						   default:  
								break;  
						}      
					});
			}, false);
	  };
	  //信息记录 文件删除(窗口模式)
	  scope.doDeleteFileForMessage=function(file,field){
			//$BPFormMethod.doDeleteFileForMessage(scope,file,field);
			var itemList=[];
			//console.log($scope.messageData.files);
			//console.log(file);
			for(var i in scope.messageData.files)
			{
				if(scope.messageData.files[i].fileId!=file.fileId)
				{
					itemList.push(scope.messageData.files[i]);
				}
			}
			scope.messageData.files=itemList;
	  };
	  scope.isInputMessageActive = function(name){
			return (scope.messageData[name]!= null && scope.messageData[name]!= ""&& scope.messageData[name]!= undefined);
	  };
	  return function (ops) {
            if (MessageModal != null) {
              MessageModal.remove();
            };
            scope.editMessageTitle = "新建"+ops.lablename;
		    scope.messageData ={};
		    if(ops.listitem!= null)
		    {
				scope.messageData = ops.listitem;
				scope.editMessageTitle = "编辑"+ops.lablename;
			}
			else{
				//初始化时间、当前处理人

				scope.userinfo = UserInfo.get();
				scope.messageData["data_id"]="";
				var s = [];
				var hexDigits = "0123456789abcdef";
				for (var i = 0; i < 36; i++) {
					s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
				}
				s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
				s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
				s[8] = s[13] = s[18] = s[23] = "-";

				var uuid = s.join("");
				scope.messageData["data_id"]= uuid;

				scope.messageData["userid_value"]=scope.userinfo.realname;
				scope.messageData["userid_realvalue"]=scope.userinfo.userid;
				scope.messageData["date_value"]=$filter('date')(new Date(),'yyyy-MM-dd');
				scope.messageData["date_realvalue"]=$filter('date')(new Date(),'yyyy-MM-dd');
		    }
            onChange = ops.onChange;
            $ionicModal.fromTemplateUrl('templates/homeApps/form/MessageEdit.html', {
              scope: scope,
              animation: 'slide-in-up'
			}).then(function (modal) {
				  MessageModal = modal;
				  MessageModal.show();
			});
      };
  }])
  //选择页面模型
  .factory('$BPUserSelectModal', ['$rootScope', '$ionicModal', function ($rootScope, $ionicModal) {
      var selcetModal = null;
	  
      var scope = $rootScope.$new(true);
      var onChange = null;
	  scope.searchData={};
	  scope.totalBaseInfo={};
      scope.selectValue = "";
      scope.closeSelectModal = function () {
          selcetModal.remove();
      };
	  scope.doSearch=function()
	  {
		  var searchValue=(scope.searchData.keyword);
		  var userAllListByDepartment = {};
		  
		  if(searchValue.length>0){
			  for (var Id in scope.totalBaseInfo) {
					var Item=scope.totalBaseInfo[Id];
					//console.log(Item);
					var Item2=[];
					for(var s=0;s<Item.UserList.length;s++){
						if(Item.UserList[s].realName.indexOf(searchValue)>=0)
							Item2.push(Item.UserList[s]);
					}
					if(Item2.length>0)
					{
						userAllListByDepartment[scope.totalBaseInfo[Id].DepartmentName]={};
						
						userAllListByDepartment[scope.totalBaseInfo[Id].DepartmentName].DepartmentName = scope.totalBaseInfo[Id].DepartmentName;
						userAllListByDepartment[scope.totalBaseInfo[Id].DepartmentName].UserList=Item2;
					}
			  }
		  }
		  else{
			  userAllListByDepartment=scope.totalBaseInfo;
		  }
		  
		  scope.userAllListByDepartment=userAllListByDepartment;
	  };
      scope.changeSelectModal = function (item) {
          if (onChange != null) {
              onChange(item);
          }
          selcetModal.remove();
      };
      return function (ops) {
          if (selcetModal != null) {
              selcetModal.remove();
          };
		  scope.searchData={};
          scope.selectValue = ops.selectValue;
		  scope.totalBaseInfo=ops.data;
		  scope.userAllListByDepartment=ops.data;
          scope.title = ops.title;
          scope.bgAllColor = ops.bgAllColor;
          onChange = ops.onChange;
          $ionicModal.fromTemplateUrl('templates/util/util-userModal.html', {
              scope: scope,
              animation: 'slide-in-up'
          }).then(function (modal) {
              selcetModal = modal;
              selcetModal.show();
          });
      };

  }])
  //判断数据是否完整
  .factory('$BPDataIsAll', function () {
      return {
          isAll: function (data, fileds) {
              for (var i in fileds) {
                  var item = fileds[i];
                  if (item.isRequire) {
                      if (data[item.id] == null || data[item.id] == "" || data[item.id] == undefined) {
                          return item;
                      }
                  }
              }
              return null;
          },
          isHave: function (data) {
              for (var i in data) {
                  var item = data[i];
                  if (item != null && item != undefined && item != "") {
                      return true;
                  }
              }
              return false;
          }
      }
  })
  
  //获取数据字典的数据
  .factory('$BPGetDataItem', ['$BPHttp', 'ApiUrl','$BPTopAlert', function ($BPHttp, ApiUrl,$BPTopAlert) {
      return function (ops) {
          $BPHttp.post({
              "url": ApiUrl.dataItemListApi,
              "data": { "enCode": ops.itemName },
              "isverify": true,
              "success": function (data) {
                  var lsdata = {};
                  var bgColorList = ["positive-bg", "royal-bg", "balanced-bg", "energized-bg", "assertive-bg", "calm-bg", "dark-bg"];
                  
				  for (var i in data.result) {
                      var item = data.result[i];
					  lsdata[i] = item;
                      lsdata[i].bgColor = bgColorList[i];
                  }
                  ops.callback(lsdata);
              },
			  "error": function () {
						$BPTopAlert.show({ text: "数据获取错误" });
			  },
			  "finally":function()
			  {
				  ops.finally();
			  }
          });
      }
  }])
  //获取表格数据的数据
  .factory('$BPGetDataTable', ['$BPHttp', 'ApiUrl','$BPTopAlert', function ($BPHttp, ApiUrl,$BPTopAlert) {
      return function (ops) {
          $BPHttp.post({
              "url": ApiUrl.dataTableListApi,
              "data": { "dbId": ops.dbId,  "dbTable": ops.dbTable,"dbFiledValue":ops.dbFiledValue,"dbFiledText":ops.dbFiledText},
              "isverify": true,
              "success": function (data) {
                  var lsdata = {};
                  var bgColorList = ["positive-bg", "royal-bg", "balanced-bg", "energized-bg", "assertive-bg", "calm-bg", "dark-bg"];
                  
				  for (var i in data.result) {
                      var item = data.result[i];
					  lsdata[i] = item;
                      lsdata[i].bgColor = bgColorList[i];
                  }
                  ops.callback(lsdata);
              },
			  "error": function () {
						$BPTopAlert.show({ text: "数据获取错误" });
			  },
			  "finally":function()
			  {
				  ops.finally();
			  }
          });
      }
  }])
  
  //工作流表单转换
  .factory('$BPFormDesign',['$AreaInfo',function ($AreaInfo) {
      return {
          "Preview": function (data,disabled) {
				//格式化数据
				var items='';
				
				for (var j = 0; j < data.length; j++) {
					var filter_id = data[j].fields.map(function (item) { if(item.isdel==0) return item.field; });
					
                    if (filter_id!=""){
						
						if(disabled){
							for(var count=0;count<data[j].fields.length;count++)
							{
								data[j].fields[count].edit = false;
							}
						}
						//开始生成数据
						for(var count=0;count<data[j].fields.length;count++)
						{
							var item=data[j].fields[count];

							if(item.isdel==0){
								//console.log(item.field);
								//文本
								if(item.fieldType=='text')
								{
									items+='<div class="item item-divider">';
									items+=item.label;
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									items+='<ion-item class="item-input">';
									//if(item.edit)
									//	items+='<div class="lr-form-input"><i class="icon ion-ios-drag"></i>'+item.label+'</div>';
									items+='<input type = \'text\' ng-model=\'editData.'+item.field+'\'  ';
									items+='ng-class="{\'active\' : isInputActive(\''+item.field+'\')}" ';
									if(!item.edit)
										items+=' ng-disabled="true" ';
									items+=' data-type="' + item.fieldType + '" data-rule="' + item.control_rule + '" data-uniq="' + item.control_uniq + '"  data-value="' + item.field + '" />';
									items+='</ion-item>';
								}
								//文本区域
								if(item.fieldType=='textarea')
								{
									
									items+='<div class="item item-divider">';
									items+=item.label;
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									items+='<ion-item class="item-input">';
									//if(item.edit)
									//	items+='<div class="lr-form-input"><i class="icon ion-ios-drag"></i>'+item.label+'</div>';
									items+='<textarea ng-model=\'editData.'+item.field+'\'  ';
									items+='ng-class="{\'active\' : isInputActive(\''+item.field+'\')}" ';
									if(!item.edit)
										items+=' ng-disabled="true" ';
									items+=' data-type="' + item.fieldType + '" data-rule="' + item.control_rule + '" data-uniq="' + item.control_uniq + '"  data-value="' + item.field + '"></textarea>';
									items+='</ion-item>';
								}
								if(item.fieldType=='texteditor')
								{
									items+='<div class="item item-divider">';
									items+=item.label;
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									items+='<ion-item class="item-input">';
									
									//items+='<div class="lr-form-input"><i class="icon ion-ios-drag"></i>'+item.label+'</div>';
									if(!item.edit){
										items+='<div class="border-around" style="width:100%" ng-bind-html="editData.'+item.field+'"></div>';
									}
									else{
										items+='<div text-angular ng-model=\'editData.'+item.field+'\' name="editor-'+item.field+'" ta-text-editor-class="border-around padding" ta-html-editor-class="border-around"></div>';
									}
									
									items+='</ion-item>';
								}
								//单选
								if(item.fieldType=='radio')
								{
									items+='<div class="item item-divider">';
									items+=item.label;
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									if(!item.edit)
										items+='<ion-item>';
									else
										items+='<ion-item ng-click="openRadioModal(\''+item.dataSource+'\',\''+item.defaultValue+'\',\''+item.label+'\',\''+item.field+'\',\''+item.dataItemCode+'\',\''+item.dbId+'\',\''+item.dbTable+'\',\''+item.dbFiledValue+'\',\''+item.dbFiledText+'\')">';
									//items+='<ion-item ng-click="openCheckboxModal(\''+item.dataSource+'\',\''+item.defaultValue+'\',\''+item.label+'\',\''+item.field+'\',\''+item.dataItemCode+'\',\''+item.dbId+'\',\''+item.dbTable+'\',\''+item.dbFiledValue+'\',\''+item.dbFiledText+'\')">';
									items+='<div class="lr-form-select" ng-hide="editData.'+item.field+'_txt != null"><i class="icon ion-ios-drag"></i>'+item.label+'</div>';
									items+='<div class="item-icon-right" ng-hide="editData.'+item.field+'_txt == null">';
									items+='<div class="lr-form-label positive-bg">{{editData.'+item.field+'_txt}}</div>';
									items+='<i class="icon ion-chevron-right icon-accessory"></i>';
									items+='</div>';
									items+='</ion-item>';
								}
								//多选
								if(item.fieldType=='checkbox')
								{
									items+='<div class="item item-divider">';
									items+=item.label;
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									if(!item.edit)
										items+='<ion-item>';
									else
										items+='<ion-item ng-click="openCheckboxModal(\''+item.dataSource+'\',\''+item.defaultValue+'\',\''+item.label+'\',\''+item.field+'\',\''+item.dataItemCode+'\',\''+item.dbId+'\',\''+item.dbTable+'\',\''+item.dbFiledValue+'\',\''+item.dbFiledText+'\')">';
									items+='<div class="lr-form-select" ng-hide="editData.'+item.field+'_txt != null"><i class="icon ion-ios-drag"></i>'+item.label+'</div>';
									items+='<div class="item-icon-right" ng-hide="editData.'+item.field+'_txt == null">';
									items+='<div class="lr-form-label positive-bg">{{editData.'+item.field+'_txt}}</div>';
									items+='<i class="icon ion-chevron-right icon-accessory"></i>';
									items+='</div>';
									items+='</ion-item>';
								}
								//下拉选择
								if(item.fieldType=='select')
								{
									items+='<div class="item item-divider">';
									items+=item.label;
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									if(!item.edit)
										items+='<ion-item>';
									else
										items+='<ion-item ng-click="openRadioModal(\''+item.dataSource+'\',\''+item.defaultValue+'\',\''+item.label+'\',\''+item.field+'\',\''+item.dataItemCode+'\',\''+item.dbId+'\',\''+item.dbTable+'\',\''+item.dbFiledValue+'\',\''+item.dbFiledText+'\')">';
									items+='<div class="lr-form-select" ng-hide="editData.'+item.field+'_txt != null"><i class="icon ion-ios-drag"></i>'+item.label+'</div>';
									items+='<div class="item-icon-right" ng-hide="editData.'+item.field+'_txt == null">';
									items+='<div class="lr-form-label positive-bg">{{editData.'+item.field+'_txt}}</div>';
									items+='<i class="icon ion-chevron-right icon-accessory"></i>';
									items+='</div>';
									items+='</ion-item>';
									
								}
								//日期 
								if(item.fieldType=='datetime')
								{
									items+='<div class="item item-divider">';
									items+=item.label;
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									items+='<ion-item>';
									if(!item.edit)
										items+='<div>';
									else
									{
										if(item.dateformat == "date")
											items+='<div ion-datetime-picker date ng-model="editData.'+item.field+'" subtitle="'+item.label+'">';
										else
											items+='<div ion-datetime-picker ng-model="editData.'+item.field+'" subtitle="'+item.label+'">';
									}
									items+='	<div class="lr-form-select" ng-hide="editData.'+item.field+' != null"><i class="icon ion-ios-drag"></i>'+item.label+'</div>';
									items+='	<div class="item-icon-right" ng-hide="editData.'+item.field+' == null">';
									if(item.dateformat == "date")
										items+='	<div class="lr-form-label positive-bg" >{{editData.'+item.field+'| date: "yyyy-MM-dd"}}</div>';
									else
										items+='	<div class="lr-form-label positive-bg" >{{editData.'+item.field+'| date: "yyyy-MM-dd HH:mm"}}</div>';
									items+='	<i class="icon ion-chevron-right icon-accessory"></i>';
									items+='	</div>';
									items+='</div>';
									items+='</ion-item>';
									
								}
								//三级联动
								if(item.fieldType=='areaSelect')
								{
									items+='<div class="item item-divider">';
									items+=item.label;
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									if(!item.edit)
										items+='<ion-item>';
									else
										items+='<ion-item ng-click="openAreaSelectModal(\''+item.baseType+'\',\''+item.field+'\');">';
									items+='<div class="lr-form-select" ng-hide="editData.'+item.field+'_txt != null"><i class="icon ion-ios-drag"></i>'+item.label+'</div>';
									items+='<div class="item-icon-right" ng-hide="editData.'+item.field+'_txt == null">';
									items+='<div class="lr-form-label positive-bg">{{editData.'+item.field+'_txt}}</div>';
									items+='<i class="icon ion-chevron-right icon-accessory"></i>';
									items+='</div>';
									items+='</ion-item>';
								}
								if(item.fieldType=='multiupload'||item.fieldType=='image'||item.fieldType=='upload')
								{
									items+='<div class="item item-divider" >';
									items+=item.label;
									if(item.edit)
									{
										items+='<i class="icon ion-ios-plus" style="float:right;font-size: 30px;" ng-click="openFileSelectModal(\''+item.fieldType+'\',\''+item.field+'\');"></i>';
									}
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									
									items+='<ion-item ng-hide="editData.'+item.field+'!=null&&editData.'+item.field+'.length>0"><div class="lr-form-select"><i class="icon ion-ios-drag"></i>'+item.label+'</div></ion-item>';
									
									
									items+='<div class="list">';
									items+='	<ion-item ng-repeat="file in editData.'+item.field+'" class="item-remove-animate mt10" ng-click="getFileContents(file)" >';
									items+='		<i class="icon ion-document"></i>';
									items+='		{{file.filename}}';
									if(item.edit){
										items+='        <ion-option-button ng-click="doDeleteFile(file,\''+item.field+'\')"><span class="lr-trash-circled"><i class="icon ion-ios-trash-outline"></i></span></ion-option-button>';
									}
									items+='	</ion-item>';
									
									items+='</div>';
								}
								//人员选择
								if(item.fieldType=='crmSelect')
								{
									//选择数据
									items+='<div class="item item-divider">';
									items+=item.label;
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									if(!item.edit)
										items+='<ion-item>';
									else
										items+='<ion-item ng-click="openCrmModal(\''+item.label+'\',\''+item.field+'\')">';
									items+='<div class="lr-form-select" ng-hide="editData.'+item.field+'_txt != null"><i class="icon ion-ios-drag"></i>'+item.label+'</div>';
									items+='<div class="item-icon-right" ng-hide="editData.'+item.field+'_txt == null">';
									items+='<div class="lr-form-label positive-bg">{{editData.'+item.field+'_txt}}</div>';
									items+='<i class="icon ion-chevron-right icon-accessory"></i>';
									items+='</div>';
									items+='</ion-item>';
								}
								//当前信息
								if(item.fieldType=='currentInfo')
								{
									items+='<div class="item item-divider">';
									items+=item.label;
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									items+='<ion-item class="item-input">';
									//if(item.edit)
									//	items+='<div class="lr-form-input"><i class="icon ion-ios-drag"></i>'+item.label+'</div>';
									items+='<input type = \'text\' ng-model=\'editData.'+item.field+'_txt\'  ';
									items+='ng-class="{\'active\' : isInputActive(\''+item.field+'\')}" ';
									items+=' ng-disabled="true" ';
									items+=' />';
									items+='</ion-item>';
								}
								//信息记录
								if(item.fieldType=='messageInfo')
								{
									
									//console.log(item);
									//item.edit=true;
									items+='<div class="item item-divider" style="height:40px;line-height:40px;">';
									items+=item.label;
									if(item.edit)
									{
										items+='<i class="icon ion-ios-plus" style="float:right;font-size: 30px;" ng-click="openMessageSelectModal(\''+item.fieldType+'\',\''+item.field+'\',\''+item.infoType+'\',null,\''+item.label+'\');"></i>';
									}
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									items+='<ion-item ng-hide="editData.'+item.field+'_list!=null&&editData.'+item.field+'_list.length>0"><div class="lr-form-select"><i class="icon ion-ios-drag"></i>'+item.label+'</div></ion-item>';
									items+='<div class="list card" ng-repeat="listitem in editData.'+item.field+'_list">';
									items+='	<div class="item item-avatar" style="min-height:auto;">';
									items+='		<div style="float:left;">{{listitem.userid_value}}</div>';
									items+='		<div style="float:right;">{{listitem.date_value}}</div>';
									items+='	</div>';
									
									items+='<div class="list" style="padding:8px;">';
									if(item.edit)
										items+='	<ion-item ng-repeat="file in listitem.files" class="item-remove-animate mt10" ng-click="getFileContents(file)" style="padding:0px;border-width:1px;border-style:solid;border-color:#EAEAEA">';
									else
										items+='	<ion-item ng-repeat="file in listitem.files" class="item-remove-animate mt10" ng-click="getFileContents(file)" style="border-width:1px;border-style:solid;border-color:#EAEAEA">';
									items+='		<i class="icon ion-document"></i>';
									items+='		{{file.filename}}';
									if(item.edit)
										items+='        <ion-option-button ng-click="doDeleteFileMessage(file,listitem,\''+item.field+'\')"><span class="lr-trash-circled"><i class="icon ion-ios-trash-outline"></i></span></ion-option-button>';
									items+='	    </ion-item>';
									if(item.edit){
										items+='<br />';
										items+='<p>';
										items+='  <button class="subdued" ng-click="openMessageSelectModal(\''+item.fieldType+'\',\''+item.field+'\',\''+item.infoType+'\',listitem,\''+item.label+'\');"><i class="icon ion-ios-compose-outline">编辑</i></button>';

										items+='  <button class="subdued" ng-click="doDeleteMessage(listitem,\''+item.field+'\')"><i class="icon ion-ios-trash">删除</i></button>';
										items+='</p>';
									}
									items+='</div>';

									items+='</div>';
								}
								//人员选择
								if(item.fieldType=='baseSelect')
								{
									//人员选择
									items+='<div class="item item-divider">';
									items+=item.label;
									if(item.verify!="")
										items+='<span>*</span>';
									items+='</div>';
									if(!item.edit)
										items+='<ion-item>';
									else
										items+='<ion-item ng-click="openBaseSelectModal(\''+item.baseType+'\',\''+item.field+'\');">';
									items+='<div class="lr-form-select" ng-hide="editData.'+item.field+'_txt != null"><i class="icon ion-ios-drag"></i>'+item.label+'</div>';
									items+='<div class="item-icon-right" ng-hide="editData.'+item.field+'_txt == null">';
									items+='<div class="lr-form-label positive-bg">{{editData.'+item.field+'_txt}}</div>';
									items+='<i class="icon ion-chevron-right icon-accessory"></i>';
									items+='</div>';
									items+='</ion-item>';
								}
							}
						}
					}
                }
				//console.log(items);
				return items;
          }
      };
  }])
//动态加载js
.factory('$BPLoadJs', ['$http', '$q', function ($http, $q) {
    return function (url) {
        var deferred = $q.defer();
        $http.get(url)
            .success(function (data) {
                eval(data);
                deferred.resolve("success");
            })
            .error(function () {
                deferred.resolve("error");
            });
        return deferred.promise;
    }
}])
.factory('$jpushService',['$http','$window','$document','$cordovaDevice',function($http,$window,$document,$cordovaDevice){
	 var jpushServiceFactory={};
	 //启动极光推送
    var _init=function(config){
        $window.plugins.jPushPlugin.init();
        //设置tag和Alias触发事件处理
        //document.addEventListener('jpush.setTagsWithAlias',config.stac,false);
		
        //打开推送消息事件处理
		if($cordovaDevice.getPlatform()=="Android")
		{
			$window.plugins.jPushPlugin.openNotificationInAndroidCallback=config.AndroidCallback;
        }
		else{
			 document.addEventListener("jpush.openNotification", config.IOSCallback, false)
		}
		//$window.plugins.jPushPlugin.receiveNotificationIniOSCallback =config.IOSCallback;
        $window.plugins.jPushPlugin.setDebugMode(true);
    }
	
	//获取状态
    var _isPushStopped=function(fun){
        $window.plugins.jPushPlugin.isPushStopped(fun)
    }
    //停止极光推送
    var _stopPush=function(){
        $window.plugins.jPushPlugin.stopPush();
    }

    //重启极光推送
    var _resumePush=function(){
        $window.plugins.jPushPlugin.resumePush();
    }

    //设置标签和别名
    var _setTagsWithAlias=function(tags,alias){
        $window.plugins.jPushPlugin.setTagsWithAlias(tags,alias);
    }

    //设置标签
    var _setTags=function(tags){
        $window.plugins.jPushPlugin.setTags(tags);
    }

    //设置别名
    var _setAlias=function(alias){
        $window.plugins.jPushPlugin.setAlias(alias);
    }
	
	
	
	var _check=function(){
		if (window.plugins) {
           return true;
        }
		else
		{
		  return false;
		}
	}


    jpushServiceFactory.init=_init;
    jpushServiceFactory.isPushStopped=_isPushStopped;
    jpushServiceFactory.stopPush=_stopPush;
    jpushServiceFactory.resumePush=_resumePush;

    jpushServiceFactory.setTagsWithAlias=_setTagsWithAlias;
    jpushServiceFactory.setTags=_setTags;
    jpushServiceFactory.setAlias=_setAlias;
	jpushServiceFactory.check=_check;
    return jpushServiceFactory;
}])
;
